Concept: Test Driven Development |  |

Relationships

Related Elements

- create unit test
- TDD

Main Description

### Description

Test-Driven Development is one of the core programming practices of XP. Many of us have learned over the years the value of writing automated tests for our code. Many of us have also learned the difficulty of writing tests after code is already in place. Test-Driven Development takes a different, extreme approach to ensure that we test all code, all the time.

The practice of Test-Driven Development requires a change in how you program and in how you think. You won't write tests as an afterthought. You won't be trying to see if the code you have written works. Instead, you will write tests as part of the everyday, every minute way of building software. Instead of writing detailed design specifications on paper, write the spec in code. Instead of first striving to perfectly design a system on paper, use tests to guide your design. Instead of coding for hours at a stretch only to find that the planning went awry, use Test-Driven Development to pace yourself, always assuring forward progress with the firm foundation of an ever-growing suite of running tests.

The steps:

- Have an idea where you are going.
- Write a test that specifies a tiny bit of functionality.
- Ensure that the test fails (you haven't built the functionality yet!).
- Write only the code necessary to make the test pass.
- Refactor the code, ensuring that it has the clear and simple design for the functionality built to date.
- Repeat until you have the desired functionality.

The rules:

- Test everything that can possibly break.
- Tests come first.
- All tests run at 100% all the time.

Test-Driven Development is infectious! Developers swear by it. Developers do not seem to abandon it after giving it an honest trial.

### Benefits

- Testable modules are decoupled from other complex classes, resulting in loosely coupled modules. Loosely coupled modules are a sign of good design.
- Code is written so that modules are testable in isolation. Code written without tests in mind is often highly coupled, a big hint that you have a poor object-oriented design. If you have to write tests first, you'll devise ways of minimizing dependencies in your system in order to write your tests.
- The tests act as documentation, providing concrete examples of how to use the module being tested.
- The tests are the first client of your classes; they show how the developer intended the class to be used.
- The tests act as a safety net. Notifying the programmer immediately when a side-effect defect is introduced into the system.
- Development is paced. You can stop at anytime with the tests describing the progress so far. Each programming session gives a sense of satisfaction with getting some of the code working.