Test-Driven Development (TDD) is a software development technique that involves repeatedly first writing a test case and then implementing only the code necessary to pass the test.
Kent Beck, who popularized TDD, defines two simple rules for TDD (Beck 2003).
- You should write new business code only when an automated test has failed.
- You should eliminate any duplication that you find. refactoring
Beck explains how these two simple rules generate complex individual and group behavior:
- You design organically, with the running code providing feedback between decisions.
- You write your own tests because you can't wait 20 times per day for someone else to write them for you.
- Your development environment must provide rapid response to small changes (e.g you need a fast compiler and regression test suite).
- Your designs must consist of highly cohesive, loosely coupled components (e.g. your design is highly normalized) to make testing easier (this also makes evolution and maintenance of your system easier too).
A Good Unit Test
For developers, the implication is that they need to learn how to write effective unit tests. Beck’s experience is that good unit tests:
- Run fast (they have short setups, run times, and break downs).
- Run in isolation (you should be able to reorder them).
- Use data that makes them easy to read and to understand.
- Use real data (e.g. copies of production data) when they need to.
- Represent one step towards your overall goal.
Why write tests first?
It's true that one can't tell if a programmer used TDD to create their unit tests or wrote them after writing the code. So why does it matter? The best reason is that it ensures unit tests actually get written.
Refactoring goes hand-in-hand with TDD, as newer unit tests drive the modification of the code. It's absolutely essential that code is continuously refactored while following the TDD workflow