TDD – Red / Green / Refactor

TDD – Red / Green / Refactor

 

It’s kind of funny that we’ve had as many Test-Driven Development (TDD) Daily Tips without ever mentioning the iterative process that makes TDD work. I’m sorry about that. I’ll right this wrong today.

The TDD cycle operates in the following way:

Step 1: Red. The Red step is the start of the cycle. We write a unit test that ‘drives’ us to create the desired behaviour in our implementation code. Since the behaviour does not yet exist, the test is destined to fail. Why red? Failing tests show up in red in UI unit testing runners. Please note that command-line runners may not show failing tests in red.

This introductory write-up on TDD explains how to create a simple failing (Red) unit test to force the writing of a ShoppingCart class. Initially, the ShoppingCart class does not exist, and we get a build error. A unit test that does not build is a failing test. Not building is failing.

Step 2: Green. Once we have our failing unit test, we move to the Green step. Our task consists of writing the implementation code to pass the test. Unit test runners usually present passing tests in green. 

In the above example, once the ShoppingCart class has been created, the unit test builds and passes, i.e. is Green.

Step 3: Refactor. Once we got the unit test to pass, we move onto the Refactor step. At this point, we will try and refactor both the test code and the implementation code. The purpose of this step is to allow us to improve the design of the code. This step is optional. There may not be anything to refactor. 

Here we have the opportunity to improve the clarity of the tests. Unit tests formalise the requirements of a system. We want tests that perform this task as clearly and concisely as possible. I’ll dive into the detail of what makes a decent unit test another time. In the meantime, if you have trouble understanding a unit test, then it is already failing in its primary purpose.

We have reached the end of the Red / Green / Refactor cycle. We return to the Red step, write our next failing unit test to drive us to implement more behaviour. 

And that is how the TDD Red / Green / Refactor cycle works.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply