Names of Tests Should Describe Features

This article is a paraphrasing of an extract from the book: Growing Object-Oriented Software, Guided by Tests, by Steve Freeman.

The name of the test should be the first clue for a developer to understand what is being tested and how the object is supposed to behave.

A common approach is to name a test after the method it is exercising, perhaps with multiple tests for the different paths through the same method. For example:

public class TargetObject{
  public void choose(Picker picker){
    ...
  }
}

public class TargetObjectTest{
  @Test public void choose(){...}
  @Test public void choose1(){...}
  @Test public void choose2(){...}
  ...
}

A better alternative is to name tests in terms of the features that the target object provides. For example, the TestDox convention, where each test reads like a sentence, with the target class as the implicit subject. For example:

  • A List holds items in the order they were added.
  • A List can hold multiple references to the same item.
  • A List throws an exception when removing an item it doesn’t hold.

We can translate these directly to method names:

public class ListTest{
  @Test public void holdsItemsInTheOrderTheyWereAdded() {...}
  @Test public void canHoldMultipleReferencesToTheSameItem() {...}
  @Test public void throwsAnExceptionWhenRemovingAnItemItDoesntHold() {...}
  ...
}

The point of the convention is to encourage the developer to think in terms of waht the target object does (i.e., its behaviour), rather than what the target object is.

The test name should should say something about:

  • the expected result
  • tha action of the object
  • the motivation for the scenario.

This method name, for example, is not clear enough:

pollsTheServersMonitorPort()

It would be better named as:

notifiesListenersThatServerIsUnavailableWhenCannotConnectToItsMonitorPort()

The above explains both the scenario and the expected result.

Speak Your Mind

*