Software Testing Best Practices

Chapter 1 · Practice 2 of 4

Push each test to the lowest level that can catch the bug

From Choosing what to test and at which level

Why it matters

Every test you write has to be maintained, so avoid checking the same thing at several levels. Fowler's advice is to push tests as far down the pyramid as you can. A validation rule for an email field belongs in a unit test of the validator, not in a browser test that types a bad email into a form.

A useful habit when a higher level test fails:

  1. Find the bug.
  2. Ask whether a lower level test could have caught it.
  3. If yes, write that lower level test first, see it fail, then fix the code.

The higher level test then only needs to prove the pieces are wired together. Its job is not to explore every branch of logic underneath.

Do

  • Write a unit test for every bug a higher level test found, before fixing it

Avoid

  • Repeating the same assertion in a unit, an integration and an end-to-end test