# Test-Driven Development (TDD) Test-Driven Development (TDD) is a software development practice where tests are written before the code they verify. Popularized by [[Kent Beck]] as part of [[Extreme Programming (XP)]], TDD inverts the traditional code-then-test approach, using tests to drive design and ensure correctness from the start. The practice follows a strict red-green-refactor cycle: write a failing test, write minimal code to pass it, then improve the code while keeping tests green. ## The Red-Green-Refactor Cycle ``` ┌─────────────────────────────────────────────────┐ │ TDD Cycle │ │ │ │ ┌───────┐ ┌───────┐ ┌──────────┐ │ │ │ RED │ ──→ │ GREEN │ ──→ │ REFACTOR │ │ │ └───────┘ └───────┘ └──────────┘ │ │ ↑ │ │ │ └─────────────────────────────┘ │ │ │ │ RED: Write failing test │ │ GREEN: Write minimal code to pass │ │ REFACTOR: Improve code, keep tests green │ └─────────────────────────────────────────────────┘ ``` ## Key Principles - **Test first**: Never write production code without a failing test - **One test at a time**: Focus on one behavior at a time - **Minimal code**: Write just enough to pass the current test - **Refactor continuously**: Clean up code after each green phase - **Fast feedback**: Tests should run in seconds ## Benefits - **Design guidance**: Tests drive better API design - **Confidence**: Changes are verified immediately - **Documentation**: Tests describe expected behavior - **Regression safety**: Catch breaks early - **Reduced debugging**: Problems isolated quickly ## Example Cycle ```python # 1. RED: Write failing test def test_add(): assert add(2, 3) == 5 # Fails: add() doesn't exist # 2. GREEN: Minimal implementation def add(a, b): return a + b # Test passes # 3. REFACTOR: Improve if needed (none needed here) ``` ## TDD vs Traditional Testing | Aspect | TDD | Test After | |--------|-----|------------| | When tests written | Before code | After code | | Design influence | Tests drive design | Tests verify existing design | | Coverage | High by default | Often incomplete | | Feedback speed | Immediate | Delayed | ## References - https://en.wikipedia.org/wiki/Test-driven_development - *Test-Driven Development: By Example* by [[Kent Beck]] ## Related - [[Kent Beck]] - [[Extreme Programming (XP)]] - [[Agile Manifesto]] - [[Continuous Integration (CI)]] - [[DevOps]] - [[Agentic TDD]]