Chapter 2 · Practice 2 of 5
Test one behaviour per test and name it after that behaviour
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 name | Better name |
|---|---|
test1 | rejects a password shorter than 15 characters |
testDiscount | does not discount orders under 100 |
it works | returns 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