Applying Test Driven Development
Applying Test-Driven Development
TDD is not "write unit tests first." It is: build a test list, pick the smallest behavior, drive it through Red → Green → Refactor, repeat.
TEXT1. Break the requirement into a test list (smallest behaviors first) 2. RED: write a failing test for the next smallest behavior 3. GREEN: write the minimum code to pass it (ugly is fine) 4. REFACTOR: improve design with tests green, no behavior change 5. Cross off the test list item, pick the next one
Minimal example (triangulation driving generalization):
Java// Test 1 → literal is acceptable assertThat(pricer.discountFor(PREMIUM, "1000.00")).isEqualTo("100.00"); // naive impl: if PREMIUM return "100.00" // Test 2 → forces real logic assertThat(pricer.discountFor(PREMIUM, "2000.00")).isEqualTo("200.00"); // now implement: subtotal * 0.10
Never skip the test list step. Without it, TDD degrades into "write a test, write some code, repeat randomly."
Progress:
- [ ] Step 1: Discover behavior via examples (Example Mapping / acceptance criteria)
- [ ] Step 2: Build a test list of small, independent behaviors
- [ ] Step 3: Pick one behavior, write a failing test (RED) for the right reason
- [ ] Step 4: Write the simplest code to pass it (GREEN)
- [ ] Step 5: Refactor with tests green (behavior-preserving)
- [ ] Step 6: Repeat until test list is empty
- [ ] Step 7: Identify boundaries (DB, network, time, external APIs) — test these at component/integration level with real or fake dependencies, not mocks of your own domain
- [ ] Step 8: Add complementary tests the TDD loop doesn't cover (contract, E2E, concurrency, security, performance) based on risk, not habit
- [ ] Step 9: Wire into CI with layered feedback speed (fast unit → integration → contract → E2E)
Step 1-2: Discovery and Test List
Don't jump to code from a vague story. Extract concrete rules first:
TEXTStory: "Premium customers get a discount on large orders" Rules (via Example Mapping): R1: STANDARD → no discount R2: PREMIUM, subtotal >= 1000 → 10% discount R3: discount capped at 250 R4: subtotal must be positive Test list: [ ] STANDARD → no discount [ ] PREMIUM / 999.99 → no discount [ ] PREMIUM / 1000 → 10% [ ] PREMIUM / 2000 → 10% (triangulation) [ ] PREMIUM / 4000 → capped at 250 [ ] subtotal <= 0 → rejected
Step 3-5: The Core Loop
- RED must fail for the right reason — the missing behavior, not a typo or compile error you didn't expect.
- GREEN: resist the urge to build the "proper" abstraction immediately. Fake it (
return 100) until a second example forces generalization (triangulation). - REFACTOR only when all tests are green. Remove duplication, fix naming, separate concerns. Never refactor and add behavior in the same step.
Step 7: Respect Boundaries
Don't mock what you own; don't fake what you don't control well.
| Layer | Approach |
|---|---|
| Domain / business rules | Classicist unit tests, no mocks needed |
| Own services calling collaborators | Real objects where cheap; stub/fake at seams |
| Database | Real engine via Testcontainers, not an in-memory substitute with different semantics |
| Payment gateway, email, external API | Stub/fake/mock — true process boundary |
| Clock, UUID, randomness | Inject as explicit interface (Clock, IdGenerator) |
Step 8: Complement, Don't Replace
TDD's inner loop proves unit/domain correctness. It does NOT prove:
- Cross-service contract compatibility → use consumer-driven contract tests (Pact-style)
- Concurrent correctness → dedicated concurrency tests + DB constraints as last line of defense
- Latency/throughput under load → performance/load tests (k6 etc.)
- Security posture → requirement-based tests (OWASP ASVS), not just "no obvious bug"
- Failure/recovery behavior → resilience/chaos experiments
Map test investment to risk, not to a fixed ratio:
TEXTRisk = probability × business impact × detection difficulty high-impact business rule → heavy unit + property tests high integration risk → component + contract + integration critical user journey → few E2E high concurrency → DB constraints + concurrency tests high security impact → ASVS-based tests high availability requirement → resilience/chaos high traffic → performance/load
Example 1: Driving a pricing rule via triangulation
Input: "Premium customers get 10% off orders ≥1000, capped at 250."
Output:
Java// RED (first failing test) @Test void premium_customer_gets_ten_percent_at_threshold() { var result = pricer.price(PREMIUM, new BigDecimal("1000.00")); assertThat(result.discount()).isEqualByComparingTo("100.00"); } // GREEN (minimal, hardcoded) if (tier == PREMIUM) return new OrderPrice(subtotal, new BigDecimal("100.00"), ...); // Second test forces generalization @Test void premium_discount_is_percentage_based() { var result = pricer.price(PREMIUM, new BigDecimal("2000.00")); assertThat(result.discount()).isEqualByComparingTo("200.00"); } // REFACTOR toward real rule var discount = subtotal.multiply(new BigDecimal("0.10")).min(MAX_DISCOUNT);
Example 2: Bug fix as regression-first TDD
Input: Production bug — duplicate orders created when the same idempotency key is sent twice under concurrent requests.
Output:
TEXT1. Write failing test reproducing the bug at the lowest possible level (sequential duplicate-key test first; concurrent test if root cause is a race) 2. Add DB unique constraint on idempotency_key as the real invariant guard 3. Catch constraint violation in application layer → return existing order 4. Confirm test goes green 5. Refactor service method for clarity 6. Add integration test with real PostgreSQL (Testcontainers) to prove the constraint actually fires — a mock repository cannot prove this
Example 3: Legacy code without tests
Input: A 2000-line untested PricingEngine class needs a new discount rule.
Output:
TEXT1. Do NOT attempt full coverage first. 2. Write characterization tests: capture *current* behavior for the inputs you're about to touch, even if that behavior looks wrong. 3. Find a seam (e.g., extract an interface around the one dependency you need to control, like a rate lookup). 4. Inject a test double through that seam. 5. Write a new failing test for the new rule. 6. Implement, make it pass, refactor only the code path you touched.
- Test list first. It's the most skipped and most valuable TDD artifact. Without it, "TDD" is just writing tests in a different order.
- Red for the right reason. A test failing due to a typo or missing import isn't the Red you want — confirm it fails because the behavior is absent.
- Baby steps + triangulation. Resist generalizing from one example. Let the second or third example force the abstraction.
- Name tests by behavior, not method.
premium_customer_gets_ten_percent_discount_at_threshold, nottestPrice1. - Inject nondeterminism.
Clock,IdGenerator, external API ports as explicit interfaces — not because "DI is good practice" abstractly, but because hidden nondeterminism makes tests flaky and unrepeatable. - Prefer real dependencies at the boundary when feasible. A real PostgreSQL via Testcontainers catches constraint/dialect/transaction issues a mock repository cannot.
- Use the correct test-double vocabulary (dummy/stub/fake/spy/mock) — sloppy terminology leads to sloppy test design arguments.
- Treat coverage as a map, not a target. High coverage doesn't mean high-quality assertions. Use it to find untested areas, not as a merge gate number to game.
- Track flaky test rate as a first-class metric. A suite nobody trusts is worse than no suite — teams start ignoring real failures.
- Match test type to risk, not to a universal ratio (no dogmatic "70% unit" rule) — align the portfolio with actual failure modes of the system.
- Definition of Done includes regression tests for every bug fix. A bug without a test will recur.
- Treating TDD as "write tests after, just earlier in the sprint" — this skips the test-list discovery and design-feedback aspects that matter most.
- Mocking every collaborator, including your own domain objects — produces tests coupled to implementation, not behavior.
- Writing a "proper" general solution on the first Green instead of letting triangulation force it — defeats the incremental-design benefit of TDD.
- Testing getters/setters or private methods — wastes effort on things with no independent risk.
- Using an in-memory fake DB (e.g., H2) when SQL dialect, constraints, or locking semantics actually matter — gives false confidence.
- Relying on
Thread.sleep, shared mutable state, or wall-clock time in tests — the #1 source of flakiness. - Retrying flaky tests until green instead of fixing or quarantining them — erodes trust in the whole suite.
- Chasing a fixed coverage percentage — teams write assertion-free tests just to touch lines.
- Using E2E tests to cover every validation combination — slow, brittle; push combinatorial cases down to unit/property tests.
- Believing TDD alone proves system qualities it was never designed to prove: concurrency correctness, security posture, performance under load, or distributed failure recovery — these need dedicated test types.
- Skipping the test list and jumping straight into code — results in large, unfocused test classes with poor behavior isolation.
- Applying one "true" school (classicist vs. mockist, inside-out vs. outside-in) dogmatically regardless of context — choose based on domain complexity, boundary location, and team conventions.