[閱讀筆記] Clean Code — Chapter 9 Unit Tests
2 min readJan 28, 2021
The Three Laws of TDD
- First Law: You may not write production code until you have written a failing unit test.
- Second Law: You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
- Third Law: You may not write more production code than is sufficient to pass the currently failing test.
Keeping Tests Clean
- Test code is just as important as production code
Tests Enable the -ilities
- Unit tests keep our code flexible, maintainable, and reusable
- Good test → improve that architecture and design without fear
- The higher your test coverage, the less your fear
Clean Tests
- Readability (clarity, simplicity, and density of expression)
- BUILD-OPERATE-CHECK pattern:
builds up the test data → operates on that test data → checks that the operation yielded the expected results
Domain-Specific Testing Language
- Test Language: a specialized API used by the tests, helps refactor their test code into more succinct and expressive forms
A Dual Standard
- Tests must still be simple, succinct, and expressive, but it need not be as efficient as production code
One Assert per Test
- Every test function in a JUnit test should have one and only one assert statement (given-when-then convention)
Single Concept per Test
- Test a single concept in each test function
- Minimize the number of asserts per concept and test just one concept per test function
F.I.R.S.T.
- Fast: Fast tests → Frequently tested→ Clean Code
- Independent: You should be able to run each test independently and run the tests in any order you like.
- Repeatable: Tests should be repeatable in any environment (the production environment, in the QA environment, and on your laptop, while riding home on the train without a network)
- Self-Validating: The tests should have a boolean output (pass or fail)
- Timely: Written just before the production code that makes them pass.
If you write tests after → production code to be hard to test → may not design the production code to be testable.