Timely
Tests should be written just before the production code
“Unit tests should be written just before the production code that makes them pass.” – Robert C. Martin
Part of the F.I.R.S.T. principles. Also known as TDD (Test Driven Development).
When to use
When developing new features or bug fixes.
Why it matters
- Design: Writing the test first forces you to design the API (Interface) before implementation. It leads to better, looser coupling.
- Coverage: If you write tests first, you never write code that isn’t tested.
Signs of Violation
- Writing a massive feature for 3 days, then spending 1 day “adding tests” (backfilling).
- “I’ll write tests later.” (You won’t).
Explanation
Problem
Writing tests after code often leads to “untestable code” because you didn’t think about dependency injection or isolation while writing it.
Solution
Red-Green-Refactor.
- Red: Write a failing test.
- Green: Write just enough code to pass it.
- Refactor: Clean up.
Real world analogy
Measuring twice, cutting once. You define the measurement (Test) before you make the cut (Code). If you cut first, you can’t easily measure if it fits without potentially ruining the material.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Test-Last Development: Writing code, then writing tests. Often results in lower quality tests.
Code example
Typescript
Good (Adherence)