CodePark/ questions / TDD & test design
START PRACTICINGPRACTICE
Backend question · Backend testing › TDD & test design

Describe the TDD cycle. What happens in each step, and why does the refactor step matter?

TDD (test-driven development) is a short loop of three steps: Red, Green, Refactor.

Red: write one small test for the next piece of behaviour. Run it and watch it fail, for the right reason. This proves the test can fail. It also pins down exactly what you want.

Green: write the simplest code that makes the test pass, even if it is naive. Don't add behaviour that no test asks for.

Refactor: now all tests are green, so clean up the code and the tests. For example:

  • remove duplication
  • improve names
  • extract functions

Run the tests after each small change. Then you know at once if you broke something.

Then repeat with the next test.

The refactor step matters because this is where the design improves. If you skip it, you get a pile of code that only passes the tests. The short loop also leaves you with a test suite that describes behaviour. You wrote it before the implementation, so the implementation could not bias it.

  • Red: write a test that fails, and fails for the right reason.
  • Green: write the simplest code that makes it pass.
  • Refactor: improve the design, with the tests as a safety net.
  • Take small steps and repeat the loop.