Test-Driven Development
test-driven development (tdd) tdd is red → green → refactor: write a failing test, write the minimum code to pass, then improve
Introduction
TDD is red → green → refactor: write a failing test, write the minimum code to pass, then improve the design. In Java/Spring projects it produces better APIs, higher coverage and fewer regressions.
Informative example
TDD cycle for a discount calculator:
// RED — test fails (class doesn't exist yet)@Testvoid noDiscountUnder100() {assertThat(calc.apply(50)).isEqualByComparingTo("50.00");}// GREEN — minimum implementationpublic BigDecimal apply(int amount) {return BigDecimal.valueOf(amount);}// RED — next requirement@Testvoid tenPercentOffOver100() {assertThat(calc.apply(200)).isEqualByComparingTo("180.00");}// GREEN → REFACTOR — extract constants, add edge cases
Best practices
- Write the test first — if you can't, your API isn't clear yet.
- Keep the green step minimal — don't over-engineer.
- Refactor only when tests are green.
Purpose of this lesson
Master Test-Driven Development so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Test-Driven Development.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Red
Write a failing test for the next requirement.
Debugging tips
- Read the full stack trace — Java's exception messages name the offending class and line.
- Reproduce in the smallest possible
main()method before fixing in the real app. - Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering
System.out.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Test-Driven Development daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain Test-Driven Development in one minute.
Q2When would you avoid Test-Driven Development?
Summary
In this lesson you learned Test-Driven Development — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.