https://enterprisecraftsmanship.com/posts/you-naming-tests-wrong/
How could the test’s name be re-written using the
[MethodUnderTest]_[Scenario]_[ExpectedResult]
convention? Probably something like this:public void Sum_TwoNumbers_ReturnsSum()
- Name the test as if you were describing the scenario to a non-programmer who is familiar with the problem domain. A domain expert or a business analyst are good examples.
Also notice that although I use the pattern
[ClassName]Tests
when naming test classes, it doesn’t mean that the tests are limited to verifying only that ClassName
. The unit in unit testing is a unit of behavior, not a class. This unit can span across one or several classes, the actual size is irrelevant. Still, you have to start somewhere. View the class in [ClassName]Tests
as just that: an entry point, an API, using which you can verify a unit of behavior.
But let’s get back to our example. The new version of the test’s name is a good start but it can be improved further. What does it mean for a delivery date to be invalid, exactly? Looking at the test, we can see that an invalid date is any date in the past. Which makes sense - you should only be allowed to choose a delivery date in the future.
So let’s be specific and reflect this knowledge in the test’s name:
public void Delivery_with_past_date_should_be_considered_invalid()
This is better but still not ideal. It’s too verbose. We can get rid of the word
considered
without any loss of meaning:public void Delivery_with_past_date_should_be_invalid()
The wording
should be
is another common anti-pattern. A test is a single, atomic fact about a unit of behavior. There’s no place for a wish or a desire when stating a fact. Name the test accordingly. Replace should be
with is
:public void Delivery_with_past_date_is_invalid()
And finally, there’s no need to avoid basic English grammar. Articles help the test read flawlessly. Add the article a to the test’s name:
public void Delivery_with_a_past_date_is_invalid()