Test-Driven Development: Red-Green-Refactor Cycle
Fast recall
Quick revision
Core answer
Whether you have actually practised TDD and understand the discipline it requires, not just the theory
Writing the full production implementation before any tests and calling it TDD — true TDD requires the test to drive the design, which often leads to better API design than implementation-first
Discuss how TDD naturally leads to testable, loosely coupled design because code that is hard to test in isolation is a design smell; and distinguish TDD from test coverage as a metric
Interview-ready guide
Interview answer
TDD is red-green-refactor: write a failing test first, write the minimum code to pass it, then refactor with the test as a safety net. The cycle repeats — each test adds one behavior, and the implementation grows incrementally.
The misconception is that TDD is about testing. It's actually a design technique. By writing the test first, you design the API before the implementation — what the method takes, what it returns, what it throws. The test is a specification.
TDD works best for business logic with clear inputs and outputs — calculators, validators, state machines. It's less useful for framework-driven code like controllers and configuration, where the design is dictated by Spring, not by your domain.
For bug fixes, TDD is invaluable: write a test that reproduces the bug, verify it fails, fix it, verify it passes. The test prevents regression permanently.
Test-Driven Development: Red-Green-Refactor Cycle
Direct Answer
TDD is a development practice where you write a failing test before writing the production code. The cycle is: Red — write the smallest possible failing test. Green — write the minimum production code to make it pass. Refactor — clean up the code while keeping all tests green. Benefits include built-in test coverage, emergent design, and a safety net for future changes. The key discipline is writing the minimal code to pass each test, then improving it in the refactor phase.
Common Mistakes & Pitfalls
Writing the full production implementation before any tests and calling it TDD — true TDD requires the test to drive the design, which often leads to better API design than implementation-first
Check your understanding
Answer these without looking back at the article.
- What is the difference between TDD and BDD (Behaviour-Driven Development)?
- How do you apply TDD when the requirement is unclear or likely to change?
- Have you encountered situations where TDD was counterproductive? How did you handle it?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.