The TDD process uses very short iterations, each adding a tiny amount of functionality to your software. Each iteration has three phases, described by the TDD mantra, "Red, Green, Refactor". The three phases are:
- Red. The colour red refers to the colour shown in many automated test runners when a test fails. The idea is that before you write any production code you should write a failing test for that functionality. This often means writing test code that exercises classes or methods that have yet to be created. It is very important that every new test fails. New tests that pass immediately suggest that either the code they test is already present or that the test itself is defective. New tests should be small, aiming to test only a single aspect of the software being developed.
- Green. The second phase of each iteration is writing code to make the new test pass. The smallest amount of code possible to make the test pass, without causing any existing tests to fail, is added to the project. This may mean creating dummy return values. For example, when creating a method that adds two values, the first test may check that adding two and three returns five. To make this test pass the method could return the fixed value of five, rather than performing an addition. Later tests will ensure that the method works correctly in all situations.
- Refactor. A very important, though often overlooked, phase is refactoring. After creating a new test and making it pass you should consider the design of the code. Sometimes no refactoring is required. Other times you might change method or property names, or extract methods for a cleaner design. In some cases you may perform major refactoring of the code for an improved design. This is made easier because the existing tests can be run to ensure no bugs are introduced during the changes.
On completion of an iteration you simply start the process again. Usually an iteration is over in minutes, so most of the time you have working, if incomplete, code.
Related articles
No comments:
Post a Comment