Test Driven Development


Red, Green, Refactor

Guidelines for Test-Driven Development | Microsoft Learn

The motto of test-driven development is "Red, Green, Refactor."

The Red/Green/Refactor cycle is repeated very quickly for each new unit of code.

  1. Understand the requirements of the feature that you are working on.
  2. Red: Create a test and make it fail.
    1. Write a unit test that won't even compile.
    2. Create the new production code stub.
    3. Run the test. It should compile but fail.
  3. Green: Make the test pass by any means necessary.
    1. Write the production code to make the test pass. Only write as much code as is required for the test to pass. If you want to write more, a new test is required.
    2. Optional: hardcode the results first to ensure that the tests are correct.
    3. When the test passes, run all tests up to make sure everything still works.
  4. Refactor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.
    1. Remove duplication caused by the addition of the new functionality.
    2. Make design changes to improve the overall solution.
    3. Rerun all the tests to ensure that they all still pass.
  5. Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/Refactor cycles.

The three laws of TDD

TheThreeRulesOfTdd

Uncle Bob describes TDD with the following rules:

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.
  2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

You must begin by writing a unit test for the functionality that you intend to write. But by rule 2, you can't write very much of that unit test. As soon as the unit test code fails to compile, or fails an assertion, you must stop and write production code. But by rule 3 you can only write the production code that makes the test compile or pass, and no more.

This results in very small iterations. He states that new tests should be added at least every 10 minutes.

The Benefits of TDD

Guidelines for Test-Driven Development | Microsoft Learn