Test Driven Development, is a programming technique based on a very simple rule:
Only ever write code to fix a failing test
In other words, write the test first, and only then write the code that makes it pass.This rule is controversial to many of us who have been schooled to first produce a thorough design, then implement the design, and finally test our software in order to find all those bugs we’ve injected during implementation. TDD turns this cycle around Test first, then code, and design afterward.
Does the thought of “designing afterward” feels awkward? That’s only natural. It’s not the same kind of design we’re used to in the traditional design-code-test process. In fact, it’s such a different beast that we’ve given it a different name, too. We call it refactoring to better communicate that the last step is about transforming the current design toward a better design.
Red-green-refactor is an alternative mnemonic for the TDD cycle of writing a test, making it pass, and making it pretty. What’s with the colors?
When we begin the TDD cycle by writing a test, it fails. It fails because our system is broken right now; it doesn’t have all the functionality we want it to have. In some development environments, it fails by displaying a red bar—thus the red in the mnemonic.
In the second step, making it pass, we implement the missing functionality so that all tests pass—both the one we just added and all the ones we had already.
At this time, the red bar turns to green, which takes us to green in the mnemonic. The last part of the cycle, refactor, is just that—refactoring. As we improve the design of the code without altering its external behavior, all tests should pass and, thus, we should remain green.
Red, green, green. Red, green, refactor. Quite catchy, isn’t it?
In its deceptive simplicity, this little cycle, test-code-refactor, encompasses a significant power to improve the overall quality of our personal software process and, subsequently, that of the whole team, project, and organization.
Reference: Test Driven PRACTICAL TDD AND ACCEPTANCE TDD FOR JAVA DEVELOPERS by LASSE KOSKELA - Manning 2008