TDD lowers regression risk and improves code design by turning requirements into executable tests before implementation, creating fast feedback and safer refactoring.
Where it came from
TDD grew from 1990s xUnit testing patterns in the Smalltalk community. Kent Beck formalized TDD within Extreme Programming (XP). The Red-Green-Refactor loop became the standard micro-cycle. TDD spread broadly through tools like JUnit, NUnit, RSpec, and pytest.
TDD grew from 1990s xUnit testing patterns in the Smalltalk community.
Kent Beck formalized TDD within Extreme Programming (XP).
The Red-Green-Refactor loop became the standard micro-cycle.
TDD spread broadly through tools like JUnit, NUnit, RSpec, and pytest.
Build your understanding
Work through these exercises in order. Try the task before opening a reference.
Write one failing unit test for a function `is_even(n)` before writing any implementation. Keep the test name behavior-focused.
Implement `is_even(n)` using the smallest change needed to pass your failing test, then add two more tests for edge cases (0 and negative values).
Given a working `calculate_total(items, tax_rate)` function and passing tests, refactor for readability (extract helper methods) without changing behavior.
A production bug shows discounts above 100% are accepted. First add a failing test that reproduces the bug, then patch the code and keep all prior tests green.
Run mutation testing on a small module and add tests that kill at least three surviving mutants. Explain what behavior each new test protects.
More ways to practice
Level 1
First Red Test
Write one failing unit test for a function `is_even(n)` before writing any implementation. Keep the test name behavior-focused.
Level 2
Green With Minimum Code
Implement `is_even(n)` using the smallest change needed to pass your failing test, then add two more tests for edge cases (0 and negative values).
Level 3
Refactor Safely
Given a working `calculate_total(items, tax_rate)` function and passing tests, refactor for readability (extract helper methods) without changing behavior.
Level 4
Bug Reproduction via Test
A production bug shows discounts above 100% are accepted. First add a failing test that reproduces the bug, then patch the code and keep all prior tests green.
Level 5
Strengthen Test Suite
Run mutation testing on a small module and add tests that kill at least three surviving mutants. Explain what behavior each new test protects.