TDD: red, green, refactor
- TDD
- test-driven development
Mid-level Frequently asked 4 min
On this page
The question
What is test-driven development?
30-second answer
A way of writing code in short loops, with the test first. Red: write a small test and watch it fail. Green: write the least code that makes it pass. Refactor: clean up while the tests stay green. Then repeat with the next behavior. The tests come out as a side effect; the main gain is that they shape the design from the caller's view.
Understand it
Red, green, refactor on a tiny kata
Step by stepRed: write a test before any code. fizzBuzz(1) should give "1". The method does not exist yet, so the test cannot even compile.
View as text
Three phases in a loop, Red, Green and Refactor, with the current one highlighted. Below them, a list of the tests written so far, each marked as passing or failing, and the code of the method.
Red: write a test before any code. fizzBuzz(1) should give "1". The method does not exist yet, so the test cannot even compile. One test fails.
Green: write the simplest code that passes. Returning the number as text is enough, even though it is clearly unfinished. One test passes.
Red: the next test says 3 gives "Fizz". The code returns "3", so the test fails for the right reason.
Green: add one rule for multiples of 3. Both tests pass, and nothing was written that no test asked for.
Red: 15 should give "FizzBuzz", but the code returns "Fizz". The new test found a case the current rule gets wrong.
Green: a rule for multiples of 15 goes first, so it wins over the rule for 3. All three tests pass.
Refactor: with every test green, clean up. Extracting divisible() removes the repeated check and changes no behavior, and the tests prove it. Then the loop starts again. All three tests still pass.
Three phases in a loop, Red, Green and Refactor, with the current one highlighted. Below them, a list of the tests written so far, each marked as passing or failing, and the code of the method.
Red: write a test before any code. fizzBuzz(1) should give "1". The method does not exist yet, so the test cannot even compile. One test fails.
Green: write the simplest code that passes. Returning the number as text is enough, even though it is clearly unfinished. One test passes.
Red: the next test says 3 gives "Fizz". The code returns "3", so the test fails for the right reason.
Green: add one rule for multiples of 3. Both tests pass, and nothing was written that no test asked for.
Red: 15 should give "FizzBuzz", but the code returns "Fizz". The new test found a case the current rule gets wrong.
Green: a rule for multiples of 15 goes first, so it wins over the rule for 3. All three tests pass.
Refactor: with every test green, clean up. Extracting divisible() removes the repeated check and changes no behavior, and the tests prove it. Then the loop starts again. All three tests still pass.
Takeaway: Each loop adds one failing test, the least code that passes it, and then a cleanup while the tests stay green, so tests drive every line.
In code
class FizzBuzzTest {
@Test
void returnsTheNumberAsText() {
assertEquals("1", FizzBuzz.fizzBuzz(1));
}
@Test
void returnsFizzForMultiplesOfThree() {
assertEquals("Fizz", FizzBuzz.fizzBuzz(3));
}
@Test
void returnsFizzBuzzForMultiplesOfFifteen() {
assertEquals("FizzBuzz", FizzBuzz.fizzBuzz(15));
}
}class FizzBuzz {
static String fizzBuzz(int n) {
if (divisible(n, 15)) return "FizzBuzz";
if (divisible(n, 3)) return "Fizz";
return String.valueOf(n);
}
private static boolean divisible(int n, int divisor) {
return n % divisor == 0;
}
}@Test void oneItem() { assertEquals(5, new Cart().add(5).total()); } // green with: return 5;
@Test void twoItems() { assertEquals(12, new Cart().add(5).add(7).total()); } // forces a real sumSolve it
Drive a password rule test first
Product wants a password check: at least 8 characters and at least one digit, with a message per broken rule. Show how you would build it with TDD, one cycle at a time.
- Write the test list first. “short is rejected”, “no digit is rejected”, “valid passes”, “both broken gives both messages”. It is a plan, not code.
- Red. Write only the first test. It fails, or does not compile because
PasswordRulesdoes not exist yet. - Green. Write the least code that passes: check the length, return one message. Resist adding the digit rule yet.
- Repeat. The digit test fails; add the rule; all tests pass. The “both broken” test forces collecting messages in a list.
- Refactor while green. Move the rules into a list of checks so a third rule is one line, and run the tests after each change.
class PasswordRulesTest {
@Test void rejectsShort() { assertEquals(List.of("at least 8 characters"), PasswordRules.check("abc1")); }
@Test void rejectsNoDigit() { assertEquals(List.of("at least one digit"), PasswordRules.check("abcdefgh")); }
@Test void acceptsValid() { assertEquals(List.of(), PasswordRules.check("abcdefg1")); }
@Test void reportsBoth() { assertEquals(2, PasswordRules.check("abc").size()); }
}
final class PasswordRules {
private record Rule(Predicate<String> ok, String message) {}
private static final List<Rule> RULES = List.of(
new Rule(p -> p.length() >= 8, "at least 8 characters"),
new Rule(p -> p.chars().anyMatch(Character::isDigit), "at least one digit"));
static List<String> check(String password) {
return RULES.stream().filter(r -> !r.ok().test(password)).map(Rule::message).toList();
}
}How to answer
- Seeing the test fail first proves that it can fail.
- Each loop takes minutes, so the code is never far from working.
- Refactoring is a required step, not an optional extra.
- Hard-to-write tests are early feedback on the design.
Common mistakes
- Describing TDD as just writing tests, without the failing test first or the refactor step.
- Writing a large batch of tests, then all the code at once.
Follow-up questions
What are the benefits and limits of TDD?
Benefits: small, testable designs, a suite you trust when refactoring, and fast feedback with little debugging. Limits: it costs more time up front, it fits poorly when you are still exploring an unknown API or a UI, and it does not catch wrong requirements or integration problems. A suite that mirrors the implementation can also slow refactoring. Use it where logic matters, and spike first when you are unsure.
- It works best for business rules with clear inputs and outputs.
- A throwaway spike is fine for learning; then rebuild the code test-first.
- Integration and end-to-end tests are still needed.
See it in the infographic: Red, green, refactor on a tiny kata
Why write the simplest code that passes, even when you know it is incomplete?
Because each line then exists for a test that demands it, so no untested or speculative code gets in. The next test forces the code to become more general; this is called triangulation. It also keeps each loop short, and a wrong guess costs minutes. Returning a hard-coded value is a legal step, as long as a later test forces it out.
- It applies YAGNI (You Aren't Gonna Need It) at the level of a single line.
- Two different examples force a general rule, where one lets you fake it.
- Clean-up belongs to the refactor step, not the green step.
See it in the infographic: Red, green, refactor on a tiny kata
Is writing tests after the code just as good as TDD?
It can give the same coverage, and good tests either way beat no tests. The difference is feedback. Written first, a test shapes the design and is seen to fail. Written later, it tends to confirm what the code already does, a bug can get locked in, and code that is hard to test is already built. Test-after works if you still check that each test can fail.
- Temporarily break the code to see a test written later fail.
- The result to judge is a trustworthy suite, not the order of writing.
- Mutation testing shows whether a suite catches changes, however it was written.
See it in the infographic: Red, green, refactor on a tiny kata
Does TDD guarantee 100% coverage?
No. Strict TDD tends to give high coverage, because every line was written to pass a test, but coverage is not the goal. It also says nothing about cases nobody thought to test. A team doing TDD can still miss a boundary or a requirement it misunderstood.
How is BDD (behavior-driven development) different from TDD?
BDD keeps the test-first loop but describes behavior in the language of the business, often as Given-When-Then scenarios that non-developers can read, with tools such as Cucumber. TDD is a developer technique at the level of code. Many teams use BDD for acceptance scenarios and TDD inside them.
Check yourself
Show answers
- Write a small test for the rule and watch it fail: Correct. The red step comes first, and it proves that the test can fail.
- Write the rule, then cover it with a test: Incorrect. That is test-after, so the test never gets to shape the code.
- Design all the classes the feature will need: Incorrect. TDD grows the design in small steps from what the tests ask for.
Show answers
- Behavior does not change, and every test stays green.: Correct. The tests are the safety net that makes the cleanup safe.
- New behavior is added along with the cleanup.: Incorrect. New behavior needs its own failing test first.
- Tests may fail until the cleanup is finished.: Incorrect. A failing test during a refactor means behavior changed, so undo or fix it right away.