Software Testing Best Practices

Chapter 2 · Practice 2 of 5

Test one behaviour per test and name it after that behaviour

From Writing good unit tests

Why it matters

Fowler's rule is to test one condition per test. When a test checks five things and fails, the first failed assertion hides the other four, and the name cannot describe all of them.

Name tests as sentences that describe behaviour, so the test report reads like a specification:

Weak nameBetter name
test1rejects a password shorter than 15 characters
testDiscountdoes not discount orders under 100
it worksreturns an empty list when the user has no orders

A good name tells you what broke before you open the file. It also exposes tests that do too much: if you need "and" in the name, split the test.

Several expect calls in one test are fine when together they check one behaviour, such as the fields of one returned object.

Do

  • Name tests after the behaviour and the condition, not the method

Avoid

  • One long test that walks through a whole feature and checks everything on the way