4 Simple Rules of simple design pt 2: Test names
Reading time: 1 minTest Names should influence an Object's API
As I've written before, tests are important. We should keep our tests as clean as our production code. With this in mind it should follow the simple rules.
I will be using the Conway's Game of Life as an example, written in C#
[code lang=java]
[Test]
public void NewWorldIsEmpty(){
var world = new World();
Assert.AreEqual(0, world.living_cells.count);
}
[/code]
This first test name indicates that it's concern with an empty world but the assert statement itself doesn't. It doesn't even have the word empty in it.
A unit test is the first consumer and the first interaction with the future concrete class (if you're doing TDD). It represents how the component(s) are going to be used.
We wouldn't want a user to have to look at the internal implementation of the world object just to found out if it's empty.
A cleaner test would look like this.
[code lang=java]
[Test]
public void NewWorldIsEmpty(){
var world = new World();
Assert.IsTrue(world.IsEmpty);
}
[/code]
This updated method reads a lot better, there's a symmetric between the name of the method and what the assert is doing, in addition it hides the internal of the object and making it a more readable API.