Understanding TDD

Now that we have seen what unit tests are and how they can help in development, we are going to learn about Test-Driven Development (TDD).

In 1996, Kent Beck introduced a new software development methodology called Extreme Programming. The word extreme indicates that the concepts behind Extreme Programming are totally different from the concepts used in software development back then. It was based on 12 rules or practices.

One of the rules states that developers have to write unit tests and all parts of the software have to be thoroughly tested. All tests have to pass before the software (or a new feature) can be released to customers. The tests should be written before the production code that they test.

This so-called Test-First Programming leads to TDD. As the name suggests, in TDD, tests drive the development. This means that the developer writes code only because there is a test that fails. The tests dictate whether code has to be written, and they also provide a measure when a feature is implemented—it is implemented when all tests for this feature pass.

Robert C. Martin (known as Uncle Bob) has come up with three simple rules for TDD:

These rules sound kind of silly because when you start with a feature that uses a new class or method that is not declared yet, the test will fail immediately, and you have to add some code just to be able to finish writing the test. But by following these rules, you will only write code that is actually needed to implement the features. And you will only write test code that is needed as well. All the code you write will either end up being part of the final product or it will be a part of your test suite.

Because of the focus on just one feature at a time, you will have a working piece of software almost all the time. So, when your boss enters your office and asks you for a demonstration of the current status of the project, you are only a few minutes away from a presentable (that is, compiling), thoroughly tested piece of software.

The normal workflow of TDD comprises three steps—the red, green, and refactor steps, respectively. The following sections describe these steps in detail.