Three laws of TDD
- You are not allowed to write any production code unless it is to make a failing unit test to pass
- You are not allowed to write any more of a unit test than it is sufficient to fail; and compilation failures are failures
- You are not allowed to write any more production code than is sufficient to pass the one failing unit test
The TDD Cycle (~10 sec long)
- You want to write some code, but you can’t because you have to write a unit test
- But after writing a line of the unit test you have to stop because it doesn’t compile
- You write a line of production code that makes the unit test pass and then you stop
- Another line of unit test that fails
- Another line of production code that makes it pass
- …
Some rules
- Duplication of code is not allowed
- You don’t add production code that makes it more specific for a test case
Advantages
- You can’t write production code that is not testable, because you write the test first
- Rids you of the fear of cleaning the code, the tests can always confirm that you didn’t break anything
- Dopamine release every time the test passes - keeps you interested
- Your unit tests become your perfect documentation
- Reduces debug time - the code just worked a minute ago
Trusting your tests
If you follow the 3 laws to the book, you will approach a 100% test coverage and thus can trust your tests