4 Simple Rules of simple design pt 2: Test names

Test 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#

[Test]
public void NewWorldIsEmpty(){
var world = new World();
Assert.AreEqual(0, world.living_cells.count);
}

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.

[Test]
public void NewWorldIsEmpty(){
var world = new World();
Assert.IsTrue(world.IsEmpty);
}

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.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s