Bookmarks

TDD — test-driven development

A development method in which an automated test for new behaviour is written before the code: first a failing test, then the minimum code that passes it, then refactoring.

Also: TDD, test-first development, test-driven design

checked 9 Nov

All terms

TDD reverses the usual order of “code first, check later”: a small test for new behaviour is written before the code itself. The test describes the expected behaviour before it is implemented, and along the way builds up a set of checks that protects the code as it changes. Kent Beck described the method in the late 1990s as part of Extreme Programming (XP).

The cycle: red, green, refactor

  1. Red: write a small test for the next behaviour and run it. It fails, because the code does not have that behaviour yet.
  2. Green: write the minimum code to make the test pass, with no speculative generalisation and no extra features.
  3. Refactor: improve both the test and the code (names, duplication, structure) and keep all tests green.

The cycle takes minutes and repeats dozens of times a day: each step is one small test and one small change to the code.

python
# 1. Red: a test for a function that does not exist yetdef test_shipping_free_from_5000():    assert shipping_cost(5000) == 0 # 2. Green: the minimum code to make the test passdef shipping_cost(order_total):    return 0 if order_total >= 5000 else 300

What it gives you in practice

  • An executable specification: the test suite describes the system’s behaviour and reads like documentation.
  • A safety net: after every change, the whole suite shows exactly what broke.
  • Interface first: writing the test first means thinking about how the function will be called before its internals.
  • Less debugging: a defect is looked for in the lines just written, not in a week’s worth of work.

Where it fits and where it gets in the way

TDD works best where tests are fast: calculations, validation, libraries, API handlers. Slow integration tests do not suit a short cycle, so they are written separately. With exploratory code, where requirements are still unclear, tests written up front only get in the way. The idea of “tests before code” is also applied at other levels: in ATDD, tests grow out of acceptance criteria, and in BDD, out of behaviour scenarios in natural language. The rule of not doing more than necessary is captured in the YAGNI principle from Extreme Programming.

Sources

the term is written from these pages

Verified 9 Nov

Not to be confused with

what it is mixed up with and how it differs

  • BDDbehaviour-driven development

    BDD describes system behaviour in natural-language scenarios, including for business requirements; TDD works at the level of code and unit tests.

  • unit test

    A unit test is the check of a single module itself; TDD is a way of working in which such a test is written first and seen to fail.