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 step

Red: write a test before any code. fizzBuzz(1) should give "1". The method does not exist yet, so the test cannot even compile.

Step 1 of 7
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.

The TDD loopWrite a test that fails. Write the least code that makes it pass. Clean up while the tests stay green. Then go back and write the next failing test.next behaviorRed: write a failingtestGreen: least codethat passesRefactor: clean up,tests stay green
The TDD loopWrite a test that fails. Write the least code that makes it pass. Clean up while the tests stay green. Then go back and write the next failing test.next behaviorRed: write a failingtestGreen: least codethat passesRefactor: clean up,tests stay green
The TDD loop

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));
    }
}
The tests, in the order they were written
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;
    }
}
The code those tests drove, after the refactor
How each test changed the codeThe test for 1 led to returning the number as text. The test for 3 added a rule for multiples of 3. The test for 15 added a rule for multiples of 15 before it. The refactor then extracted a divisible method with no change in behavior.fizzBuzz(1) is 1Return the numberas textfizzBuzz(3) is FizzAdd the rule for 3fizzBuzz(15) isFizzBuzzAdd the rule for 15,firstExtract divisible()
How each test changed the codeThe test for 1 led to returning the number as text. The test for 3 added a rule for multiples of 3. The test for 15 added a rule for multiples of 15 before it. The refactor then extracted a divisible method with no change in behavior.fizzBuzz(1) is 1Return the numberas textfizzBuzz(3) is FizzAdd the rule for 3fizzBuzz(15) isFizzBuzzAdd the rule for 15,firstExtract divisible()
How each test changed the code
@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 sum
Fake it, then a second example forces the real code

Solve 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.

  1. 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.
  2. Red. Write only the first test. It fails, or does not compile because PasswordRules does not exist yet.
  3. Green. Write the least code that passes: check the length, return one message. Resist adding the digit rule yet.
  4. Repeat. The digit test fails; add the rule; all tests pass. The “both broken” test forces collecting messages in a list.
  5. 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();
    }
}
The tests that drove it, and the code after the refactor

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

1. You are about to add a discount rule using TDD. What do you do first?
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.
2. What must hold during the refactor step?
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.