Chapter 2. Test-Driven Development

Your first response to Test-Driven Development, or TDD, may be that it feels like a good way to encourage developers to write their unit tests. After you have spent some time with TDD, however, that becomes its least interesting aspect. Let's take a quick look at what TDD is and where it came from, then move on to the fascinating parts.

Test-Driven Development arose out of early literature around XP and other agile methods and was put forth, first and foremost, as a way to support refactoring. The idea was that writing your tests first forced you into thinking about tests, which in turn encouraged you to write more. The more tests you had, the easier it was to practice refactoring, or the art of making small incremental changes to your code to improve its structure. Proper refactoring involves making very small organizational changes to your code, then making sure that your tests still pass. Without proper test coverage, refactoring is much more difficult.

See Martin Fowler's excellent book Refactoring: Improving the Design of Existing Code (Addison-Wesley, 1999) for more information on this practice.

The process of TDD is often described, in abbreviated form, as "Red, Green, Refactor," meaning that first you write tests so that the tests fail (causing a "red light" in most testing GUIs), then you write code to make the tests pass (causing the "light" to turn green), and then you are free to refactor or improve the structure of your code, safe ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.