Testing One Two Three: TDD Explained
TDD, or “Test-driven development” refers to a style of programming in which it depends on a set of three activities: coding, testing, and design. TDD can be simply described by the following these set of rules: write a “single” unit test describing an aspect of the program, run the test, which should fail because the program lacks that feature, write “just enough” code — the simplest possible — to make the test pass, “refactor” the code until it conforms to the simplicity criteria, and repeat, “accumulating” unit tests over time.
The idea of TDD goes as far back as 1968, where old articles and papers describe the process of testing the specification before writing the code. Then in 2003, a book titled “Test Driven Development: By Example” was published. It was written by Kent Beck, who is considered by many to be the father of TDD, and the book itself is commonly referred to as the bible of TDD. While it was not Kent Beck who invented TDD, he definitely was the one who made it popular.
TDD is a predictable way to develop code which relies on the following three steps:
RED — Write a unit test, run it and watch it fail. The unit test should be short and focus on a single behavior of the system under test. By writing the failing test you ensure that your test is calling the correct code and that the code is not working by accident. It’s a meaningful failure, and you expect it to fail.
GREEN — Write the minimum amount of code needed to make the test pass.
REFACTOR — Eliminate the duplication (both in the test and in the code, including duplication between test and code).
When using TDD, developers will gain benefits such as:
- Allowing members to write smaller codes with single responsibility rather than big ones.
- Results in better designed and maintainable code.
- Helps other team members to understand how the code will be use and interact
- Able to notice breaks in the code by having a set of automated tests that can be easily fixed
- Faster, more extensible code with fewer bugs that can be updated with minimal risks
- Other team members can easily pick up and work on the code
- Resulting in cleaner code by writing test cases
TDD is crucial in fast-moving, agile environments — but it can cause drawbacks for developers if not handled properly. Writing the tests in the early stages can slow the development process, which could be frustrating. In complex cases, it can be difficult to effectively define and test everything you will need to. It also does not guarantee the quality of unit tests. Instead, all the focus goes into defining metrics.
References: