Test-driven development (TDD) is a technique for building software where tests are written to guide software development. Developed by Kent Beck in the late 1990s as part of Extreme programming. Essentially, we follow three simple steps iteratively:
- Write tests for the next feature you want to add.
- Write functional code until the tests pass.
- Refactor both new and old code to structure it well.
Although these three stages are often summarized as: Red – Green – Refactoring, is the core of the process and also has an important initial step of first creating a list of test cases. Then select one of these tests, apply red-green-refactoring to it, and select the next test when complete. Sequencing your tests correctly is an art. We want to choose tests that get us quickly to important points in the design. Along the way, we need to add more tests to the list as they arise.
Writing tests first, which XPE2 calls Test-First programming, offers two main advantages: The most obvious one is how to get SelfTestingCode since you can only write some functional code in response to a test passing. The second benefit is that thinking about tests first forces you to think about the interface to your code first. This focus on how interfaces and classes are used helps to separate the interface from the implementation, a key element of good design that many programmers struggle with.
The most common way to mess up TDD is to ignore the third step. Refactoring to keep your code clean is a key part of the process. Otherwise you end up with a messy set of code fragments. (The consequences are less painful than most design failures, because at least they get tested.)
revision
The original post on this page was 2005-03-05. Inspired by Kent’s canonical post, updated on 2023-12-11.