Test-driven development

By Allen Jay Bercero

Test-driven development (TDD) is a practice where you write a small automated test before writing the code it checks, then write just enough code to make the test pass, then clean up the design. You repeat that in tiny cycles. TDD is as much a design discipline as a testing one: writing the test first forces you to shape code that is simple and easy to use.

It was popularized by Kent Beck as part of Extreme Programming and set out in his 2002 book Test-Driven Development: By Example.

Also known as

TDD · test-first development · test-first programming

Don't confuse with

  • Writing tests afterwards (“test-last”): TDD writes the test first, so the test drives the design. Testing existing code is valuable, but it isn’t TDD.
  • BDD and ATDD: TDD works at the developer/unit level (“am I building it right?”). BDD and ATDD work at the feature/behavior level with the whole team (“am I building the right thing?”).
  • Unit testing (the tool): TDD uses unit tests, but TDD is the practice of writing them first, not the tests themselves.

The cycle: red, green, refactor

  1. Red: write a small test for behavior that doesn’t exist yet. Run it; it fails (the test bar is red).
  2. Green: write the simplest code that makes the test pass, even if it’s crude.
  3. Refactor: with the test now protecting you, clean up the code (and the test) without changing behavior.

Then pick the next small behavior and repeat. The steps are deliberately tiny, often only minutes each.

In plain English

Say what the code should do (as a test), make it do that, then tidy up. Repeat in small steps, always with a safety net.

Why teams do it

  • Design pressure: code that’s hard to test is usually badly designed, and writing the test first surfaces that early.
  • A regression safety net: the accumulated tests catch breakage the moment it happens.
  • Living documentation: the tests show, precisely, what the code is supposed to do.
  • Confidence to change: you can refactor freely, because the tests will tell you if you broke something.

See also

References