TDD
Red-green-refactor cycle, mock vs stub vs spy, test doubles
Test-Driven Development (TDD) is a development discipline where tests are written before production code, driving the design through a tight Red-Green-Refactor cycle: write a failing test (Red), write the minimal code to pass it (Green), then improve code quality without changing behavior (Refactor). TDD produces designs with inherently high testability, low coupling, and explicit interfaces, since code must be testable by construction. Kent Beck, who formalized TDD with Extreme Programming, and Google's engineering research both show TDD-authored code has 40–80% fewer production defects.
Key Points
- Red phase: write one small failing test that describes the desired behavior — do not write any production code yet.
- Green phase: write the simplest code that makes the test pass — duplication and shortcuts are acceptable here.
- Refactor phase: improve naming, eliminate duplication, apply patterns — all tests must remain green throughout.
- Mock: a test double that records interactions and allows assertions on whether methods were called with expected arguments.
- Stub: returns pre-defined responses to calls, controlling indirect inputs — does not verify interaction, only controls output.
- Spy: wraps a real object, recording calls while delegating to the real implementation — use when you need partial mocking.
- Fake: a lightweight working implementation (e.g., in-memory database) — more realistic than mocks, simpler than real dependencies.
- Outside-in TDD (London school): start with a failing acceptance test, drive inward to unit tests — favors mocks at boundaries.
- Inside-out TDD (Chicago school): start with domain logic units, build outward — produces simpler designs, avoids over-mocking.
Real-World Example
Google's internal codebase uses a TDD-inspired workflow enforced at code review: new public APIs must ship with tests demonstrating intent. Their Abseil C++ library was developed with 100% TDD, achieving near-zero production defects over its first three years.