Test-driven development is based on the results of test cases you define. The cyclical approach ensures that the code is only applied to the functioning system once all requirements on the software are met. This means that you refactor and retest code components as often as necessary until the test is no longer failed. This method allows you to gradually augment the software with new functions, since you write a new piece of source code after each test is passed. For this reason, TDD is also considered an incremental model of software development.
Individual test cases typically go through the cycle for no longer than a few seconds or minutes. This way, the results can quickly be seen in the functioning code. For efficient iteration, you’ll need a TDD tool and framework. Usually, developers use a tool for build automation like CruiseControl or Jenkins. These enable the continuous and faultless integration of components in the source code. JUnit, Maven, and Ant are also popular in Java development. In general, the tests are always written in the same language as the functioning code. For PHP, you can use tools like Ceedling or CMock, for example.
But how is the test method applied? The cycle which programmers follow in test-driven development is also known as the red, green, refactor cycle. This describes the individual phases that you go through for maximum efficiency:
- Red phase: In this phase, the user perspective is considered which means that code needs to be simple. In other words, you write a test that contains components that have not yet been implemented. Therefore, you need to make a decision on the elements that are essential for a piece of code to work.
- Green phase: Let’s assume the test fails and is marked red.You now step into the role of a programmer who tries to find a simple solution. Most importantly, you only write as much code as necessary. You then integrate it into the functioning code so that the test is marked green.
- Refactoring: In this step, the functioning code is “tidied up” and perfected in its structure. This means that you should amend and restructure it so that it becomes simple and elegant to read from a developer’s perspective. Steps involved include removing duplicated code, for example.
Make sure that the individual activities do not overlap, i.e. don’t write tests in Phase 2 or 3 or functioning code in Phase 1 and 3. The following video shows how test-driven development works in practice: