Tests are an investment that should pay back in confidence and speed. The testing pyramid is a rule of thumb for spending that investment.
The three levels
- Unit tests check a small piece of logic in isolation, such as a function or a class. They run in milliseconds, fail with a precise location and need no infrastructure. You should have the most of these.
- Integration tests check that parts work together: your code with the database, a queue or an HTTP client. They are slower, but they find the bugs that happen at the seams, such as wrong SQL or serialisation mistakes.
- End-to-end tests drive the whole system through the user interface or the public API. They are the most realistic and the slowest and most fragile, so keep them for the critical journeys, such as sign-up and checkout.
Why a pyramid
Lower levels are cheap, fast and stable, so many of them give quick feedback. Higher levels are costly and flaky, so a few of them cover the most important paths. An upside-down pyramid, with mostly slow browser tests, makes a suite that nobody wants to run.
def discount(total, is_member):
if total < 0:
raise ValueError("total must not be negative")
return total * 0.9 if is_member else total
# A unit test: small, fast and exact.
assert discount(100, True) == 90
assert discount(100, False) == 100What makes a test good
- It tests behaviour, not implementation details, so refactoring does not break it.
- It is deterministic. Control the clock, randomness and the network.
- It is independent from other tests and can run in any order.
- A failure message tells you what broke.
Anti-patterns
- Flaky tests that fail sometimes teach the team to ignore red builds. Fix or delete them quickly.
- Mocking everything, until the test checks only the mocks.
- Chasing a coverage number instead of testing risky logic.
Takeaway
Write many fast unit tests for logic, enough integration tests for the seams and a few end-to-end tests for the journeys that must never break.
Comments