Concept · Testing practice

Red, green, refactor

The test-driven development loop: write a failing test, make it pass with the simplest code, then clean up while the tests stay green.

2 minTDDtest-driven developmenttest firstthree laws of TDD

Red, green, refactor is the core loop of test-driven development, described by Kent Beck in Test-Driven Development: By Example (2002). Each cycle takes minutes:

  1. Red. Write one small test for the next piece of behaviour. Run it and see it fail — for the reason you expect.
  2. Green. Write the simplest code that makes it pass. Hard-coding the answer is allowed.
  3. Refactor. With every test passing, improve names and structure in both code and tests. Run the tests after each change.

Then pick the next behaviour and repeat.

Why each step matters

  • Seeing red proves the test can fail. A test with a wrong assertion, a misspelled name, or no assertion at all passes vacuously — and you'd never know.
  • Doing the simplest thing keeps steps tiny. Hard-coding return 15000 feels like cheating, but the next test (a second example — "triangulation") forces the general solution, and you never write code no test asked for.
  • Refactoring on green is safe because the tests catch mistakes immediately. Skipping it is the most common way TDD goes wrong: you get tests, but code that grows messier with every cycle.

Rules of thumb

  • If a cycle takes more than ten minutes, the step was too big. Revert and write a smaller test.
  • One failing test at a time.
  • Refactor tests too — they're code that must be read and maintained.
  • Commit on green; it gives you a safe point to return to.

Beck's companion "three laws of TDD", as phrased by Robert Martin, make the same loop strict: write no production code except to pass a failing test; write only enough of a test to fail; write only enough code to pass.

Where it fits

The loop drives design as much as testing: code written test-first ends up with small units and explicit dependencies, because anything else is awkward to test. It's also the rhythm behind ping-pong pairing, where partners alternate writing the failing test and making it pass. The TDD lesson walks through a complete session, and the test pyramid describes the mix of tests the loop should produce.

Learn it in depth