Naming Tests

Good naming unit tests, or any tests for that matter is crucial to error localization and maintenance of the test suite. In essence it’s quite simple: A test name should convey what’s specific about the test and the expected outcome of the test. There are close to ten naming standards out there, but they are variations of each other to a large extent. Here, the three most prevalent will be presented, along with a fourth one, which is the recommended one by this site.

Imagine we’re writing a unit test to exercise a scenario in the checkout step of an online shopping flow. Just before entering their payment details, loyal customers (whatever that means) are supposed to get a small discount.

UnitOfWork_StateUnderTest_ExpectedBehavior

Naming standard popularized by Roy Osherove, originally from the .NET world, hence the underscores. Clear, simple, and readable. A possible drawback is that the unit of work may be hard identify and it can get repetitive without adding too much information to the test.

Produces:

Checkout_LoyalCustomers_Get5PercentDiscount()

BDD-style: something should

Naming standard popularized by Dan North in conjunction with BDD. Produces a nice statement about what should happen. In some cases the phrasing may sound awkward and one might argue that “should” isn’t definitive. “What if it doesn’t?” Still, it’s a good standard.

Produces:

shouldGive5PercentDiscountToLoyalCustomers()

Mandated by frameworks without metadata: test something

A fair share of testing frameworks can’t or won’t use metadata like annotations or attributes to identify tests. A valid reason is that the programming language doesn’t support such functionality, which is why they must rely on introspection and a naming convention to find the tests to execute.

In theory it shouldn’t be a problem. The mandatory prefix, test or t_, would be treated as noise and a reasonable name would follow. For example:

testGive5PercentDiscountToLoyalCustomers

or

testLoyalCustomersGet5PercentDiscount

However, what most codebases sadly end up with is: testCheckout. Therefore, for the sake of simplicity, stay away from this scheme altogether.

Recommended scheme: a definitive statement

This site recommends that the test name be a definitive statement about some functionality—a specification. That way, the name is readable to non-technical stakeholders, it doesn’t carry a potentially redundant prefix(unit of work), and it’s non-ambiguous (no shoulds).

Produces:

loyalCustomersGet5PercentDiscount()

The caveat

Context is king when naming tests. Certain designs and tests literally scream for a specific naming standard (though no conditions will scream for test… scheme), so be prepared to experiment and abandon your favorite scheme.