Chapter 9 - Unit Tests
-
The Three Laws of TDD
- You may not write production code until you have written a failing unit test.
- You may not write more of a unit test than is sufficient to fail. Not compiling counts as failing.
- You may not write more production code than is sufficient to pass the currently failing test
-
Test code is just as important as production code. It requires thought, design and care and must be kept as clean as production code.
-
Unit tests keep code flexible, maintainable and reusable, as tests enable change.
- If you have tests, you don't fear making changes as you have guarantees that you haven't caused a regression.
- The dirtier your tests, the dirtier your code becomes.
-
Readable tests are clean tests
- Extract duplicate code so that the purpose of each test becomes more clear.
- Make tests simple, succinct and expressive.
- No need to make it as efficient as production code.
-
Build-Operate-Check Pattern: Split your test into 3 parts:
- Build up test data
- Operate on the test data
- Check that the operation yielded the expected results
-
Use a domain-specific testing language
-
Minimize the number of asserts in a test (keep it to one assert if you can)
-
Keep to a single concept in each test
-
F.I.R.S.T. rules for Clean Tests:
- Fast - Tests should run quickly. If tests are slow, you won't want to run them frequently.
- Independent - Tests should not depend on each other
- Repeatable - Tests should be repeatable in any environment
- Self-Validating - Tests should have a boolean output (PASS or FAIL)
- Timely - Write tests just before writing the code that makes them pass. If you write tests after the production code, you may find it hard to test.