Good Naming of Unit Tests

A couple of posts ago I spoke about Good Naming, and amongst other things outlined some principles that can be followed when choosing good names for methods or functions.

There is of course one type of method which is an exception to these rules: the unit test. Unit tests are unique methods in that we never call them. They are called by our unit testing framework only. For this reason, they should be afforded their own set of principles when naming them.

When I read the name of a unit test I hope it will tell me, at a high level, the following three things:

  • What is the unit being tested?
  • What are the conditions under which it is being tested?
  • What is the expected result?

As such, unit test methods can and usually should be long.

Personally I name my unit tests using a [unit]_[conditions]_[expectation] pattern, but as long as you include all of this information in your unit test name, the order and pattern you use aren’t really important. Obviously if you are adding to an existing codebase then you should try to avoid introducing inconsistencies.

Here are some examples of good unit test names following my preferred pattern:

  • GetAddress_InvalidUserId_ThrowsException
  • GetAddress_ValidUserId_ReturnsAddress
  • UpdateAddress_ValidParameters_CallsRepositoryMethod
  • GetSquareRoot_NegativeInteger_LogsError
  • GetSquareRoot_NegativeInteger_ThrowsException
Share Button