The following is an excerpt from my book Effective Unit Testing. It walks you through the TDD process in great details.
Test Driven Development, or TDD, means you write a failing test first, and add as little code as possible to make it pass. As you go, there can be multiple steps you need to take before a test eventually passes. When all your assertions are verified, your feature is complete. Therefore, when all tests pass, your app code will already be covered by unit tests. You don’t need to spend extra time to add tests afterward. There are a lot of resources about the process of TDD on the Internet, so I’m not going to elaborate it here.
The Red-Green-Refactor TDD Cycle
In essence, TDD is performed with the Red-Green-Refactor cycle. The three steps are:
- RED – Write a failing test
- GREEN – Write the minimum amount of code to make the test pass
- REFACTOR – Refactor both the app code and test code
You write a failing test to go into the RED state. Next, you write just enough code to transition to the GREEN state. Finally, you REFACTOR both your app code and test code while staying in GREEN. You then move on to the next test.
The Ordered Steps of TDD
Some people think they should write the assertions to fail first. But I have a different take on this. At the beginning, you don’t even know what the function signature looks like. You just draw a blank. It’s hard to write an assertion. What is the name of the function, its arguments (if any), the return value (if any)? Is it synchronous or asynchronous? Does it return results in a delegate method? Any optionals or nil’s we need to account for? Will it generate errors?