Naming Tests by Scenario and Outcome

A useful test name states the situation and the expected behavior so a failure can be understood outside the file.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Include the boundary
  2. Avoid incidental implementation details
  3. Name the boundary that matters to the result
  4. Use a different name for a different obligation

Include the boundary

A name indicating that a search of an empty sequence returns a missing result describes both its input and output. A name like test_search_2 gives neither. Match the wording in the function contract.

Avoid incidental implementation details

A label saying “returns existing entry when the caller sets the same value twice” remains useful across refactoring. A label naming a particular internal method can go stale. The goal is discoverability when looking at test action and assertion.[1]

Name the boundary that matters to the result

A cache test called test_cache_2 gives little clue when it fails. A name expressing “reading at the exact expiry returns a miss” identifies both scenario and promise. It helps reviewers see why the exact timestamp belongs in the fixture. See testing with a fake clock.

Scenario: existing value and time exactly at expiry
Action: look up its key
Outcome: miss under an inclusive expiry contract

Use a different name for a different obligation

A check that verifies cleanup of an expired item concerns stored state as well as the return value. Make that meaningful in the name or add a separate test. Avoid basing the name on a helper call unless the helper is itself the public contract.

References

  1. Python Software Foundation, unittest: Unit Testing Framework ↩