Test-Driven Development

November 27, 202611 minutes

Part 5 of 5

Write the test first. Follow the red-green-refactor loop on a real rule, see why small steps keep mistakes cheap, and learn the practices and pitfalls that decide whether TDD helps.

Here is a strange order of work: write the test first, before the code exists. It sounds backwards, because you can’t test something that isn’t there yet. But try it on a real change. The shipping calculator needs a new rule: parcels over twenty kilograms pay a heavy-parcel surcharge of ten dollars. Most of us would write the rule, then maybe add a test. Test-driven development (TDD) flips that. The test comes first, fails, and then tells you when the rule is done.

Prefer to watch? The narrated video covers the same lesson (about ten minutes). The article follows it section by section, with diagrams and a little extra depth.

This is the last lesson of a series on testing in Java. It builds on unit testing with JUnit 5, code coverage with JaCoCo, mutation testing with PIT and test doubles with Mockito. Every lesson reuses the same small shipping calculator.

A climber’s anchors

A climber on a long route clips the rope into an anchor every few metres. The anchors don’t make the climb any easier. They change what a fall costs. With no anchors, a slip far up the wall is a long fall. With an anchor every few metres, a fall only drops you to the last one.

In TDD, each passing test is an anchor. You write a small piece of code and run the tests. If something breaks, you only lose the last step. That is why the steps are tiny: the shorter the climb between anchors, the less a mistake costs.

The climber's anchors mapped onto TDD: a passing test is an anchor, a small step is a short climb between anchors, a red test is a fall that stops at the last anchor, and a big step is a long climb with no anchors. The climber's anchors mapped onto TDD: a passing test is an anchor, a small step is a short climb between anchors, a red test is a fall that stops at the last anchor, and a big step is a long climb with no anchors.
The climb, mapped onto the lesson.

The loop: red, green, refactor

The loop has three colours. Red: write one failing test. Green: make it pass with the simplest code that works. Refactor: clean up, with the tests still green. One pass through the loop takes minutes, not hours. Martin Fowler describes the same three steps: write a test for the next bit of functionality, write the code until it passes, then refactor both the new and the old code.

The red-green-refactor loop: a failing test (red) leads to the simplest passing code (green), which leads to a cleanup with the tests still green (refactor), which leads back to the next failing test. The red-green-refactor loop: a failing test (red) leads to the simplest passing code (green), which leads to a cleanup with the tests still green (refactor), which leads back to the next failing test.
Three stops, round and round.

Kent Beck, who wrote the book on this, adds a test list. Before you start, write down the scenarios you can think of. Then take them one at a time, never all at once. (In his “Canon TDD” post the steps are: write a list, turn exactly one item into a runnable test, make it and all the earlier tests pass, optionally refactor, and repeat until the list is empty.)

Robert Martin puts it as three rules: no production code without a failing test; no more of a test than it takes to fail; and no more production code than it takes to make that test pass.

Test after is different. The code is already there, so the test tends to describe what the code does. Test first describes what the code should do, and has to fail before it passes.

We will run the loop on the heavy-parcel rule. The order now carries its weight in kilograms, and the rest of the calculator is unchanged:

public record Order(double total, boolean express, double weightKg) {}

The test list

Here is the calculator as it stands:

public double cost(Order order) {
    double shipping;
    if (order.total() >= 100) {
        shipping = 0;
    } else {
        shipping = 7.99;
    }
    if (order.express()) {
        shipping += 15;
    }
    return shipping;
}

Before any test, we write the list:

  1. A heavy parcel on a free-shipping order pays ten extra.
  2. A heavy parcel on a small order pays the flat rate plus ten.
  3. A parcel of exactly twenty kilograms pays nothing extra.

The list describes behaviour, not design. It says what the calculator does, not how. The order matters too, so start with the item that teaches you the most, and tick items off as you go.

Red: see it fail for the right reason

Pick the first item and write its test. A parcel of 25 kilograms on a free-shipping order should cost exactly ten. It has the same shape as the tests in the JUnit lesson.

@Test
void heavyParcelPaysSurcharge() {
    assertEquals(10.0, calc.cost(new Order(120, false, 25)), 0.001);
}

Now run it. It must fail, and for the right reason. Here it expected 10.0 and the calculator returned 0.0:

expected: <10.0> but was: <0.0>

That is the missing surcharge, exactly what we want to see. Failing for the wrong reason, like a compile error, tells you nothing. And a test you never saw fail may never be able to.

Green: fake it

Now make it pass with the simplest code that could work. A hard-coded answer is fine. If the weight is over twenty, return ten.

public double cost(Order order) {
    if (order.weightKg() > 20) {
        return 10;
    }
    double shipping;
    if (order.total() >= 100) {
        shipping = 0;
    } else {
        shipping = 7.99;
    }
    if (order.express()) {
        shipping += 15;
    }
    return shipping;
}

Yes, that is a fake. It ignores the total and the express fee. But the test is green, and we have set our first anchor. Beck calls this faking it: return a constant to get to green quickly, and let the next test force the real code. Starting small gets you to green in a minute, so any surprise shows up while the step is cheap.

Triangulate

The fake only survives until the next test. A heavy parcel on a small order should pay the flat rate plus ten, which is 17.99.

@Test
void heavySmallOrderPaysFlatRatePlusSurcharge() {
    assertEquals(17.99, calc.cost(new Order(50, false, 25)), 0.001);
}

Run it. Red. It expected 17.99, and the fake returned 10.0:

expected: <17.99> but was: <10.0>

Two examples now disagree with the constant, so the real rule appears. Add the surcharge to the shipping, instead of returning it:

public double cost(Order order) {
    double shipping;
    if (order.total() >= 100) {
        shipping = 0;
    } else {
        shipping = 7.99;
    }
    if (order.express()) {
        shipping += 15;
    }
    if (order.weightKg() > 20) {
        shipping += 10;
    }
    return shipping;
}

Both tests pass. Beck calls this triangulation: you generalise the code only when two examples demand it. (7.99 plus 10 is 17.990000000000002 in a Java double, so the test uses a delta of 0.001, as in the JUnit lesson.)

When the rule is obvious, you can type it straight away. Faking it and triangulating are the careful route, for when you are not sure what the code should look like.

Choosing how to get to green: if the rule is obvious, type it; if not, fake it with a constant, and let a second example force the real rule (triangulation). Choosing how to get to green: if the rule is obvious, type it; if not, fake it with a constant, and let a second example force the real rule (triangulation).
Pick a step size to match your confidence.

Refactor with the tests green

Now refactor, with both tests green. The numbers 20 and 10 are magic, so give them names:

private static final double HEAVY_KG = 20;
private static final double HEAVY_SURCHARGE = 10;

public double cost(Order order) {
    double shipping;
    if (order.total() >= 100) {
        shipping = 0;
    } else {
        shipping = 7.99;
    }
    if (order.express()) {
        shipping += 15;
    }
    if (order.weightKg() > HEAVY_KG) {
        shipping += HEAVY_SURCHARGE;
    }
    return shipping;
}

Tests are code too. Both build the same order, so pull that into a small helper. Run everything again, and it stays green:

private double costOf(double total, boolean express, double kg) {
    return calc.cost(new Order(total, express, kg));
}

@Test
void heavyParcelPaysSurcharge() {
    assertEquals(10.0, costOf(120, false, 25), 0.001);
}

@Test
void heavySmallOrderPaysFlatRatePlusSurcharge() {
    assertEquals(17.99, costOf(50, false, 25), 0.001);
}

Refactoring never changes behaviour, and the green tests are the proof. That safety net is what lets you clean up without fear. New behaviour waits for the next red test.

The boundary: a test that passes at once

The last item on the list: exactly twenty kilograms pays nothing extra. Boundaries are where bugs live, as the JUnit lesson showed. Write the test:

@Test
void exactlyTwentyKgPaysNoSurcharge() {
    assertEquals(7.99, costOf(50, false, 20), 0.001);
}

Run it, and it passes at once. A test that never failed is suspicious, so break the rule on purpose. Change greater-than to greater-than-or-equal in the condition:

if (order.weightKg() >= HEAVY_KG) {

Run it again:

expected: <7.99> but was: <17.990000000000002>

Red, so the test can fail. Change it back, and it is green again. The list is empty, with three tests and three anchors.

CycleTestRedGreen
1heavy parcel, free shippingexpected: <10.0> but was: <0.0>fake: return 10
2heavy small orderexpected: <17.99> but was: <10.0>real rule: shipping += 10, then refactor
3exactly 20 kggreen at once; red after flipping > to >=flip back

Best practices

  1. Tiny steps. Each cycle adds one behaviour, in minutes. If a step takes an hour, split it.
  2. Keep a test list, and add to it as you learn. Write one test from it at a time, never all of them.
  3. See each test fail first, and for the right reason. A test that has never been red hasn’t proved anything, because it might pass for the wrong reason.
  4. Always refactor, and that includes the tests. Duplication is a hint, not a command, so tidy when the pattern is clear.
  5. Commit on green. Every green state is an anchor in version control, so you can always step back to the last one. (This one is our recommendation, not part of Beck’s loop.)
  6. Listen to the design. If a test is painful to write, the code is telling you something: too many dependencies, hidden state, or a class doing too much. Fowler notes that writing the test first separates interface from implementation, a key element of good design.

Pitfalls: how the loop breaks

  1. Writing many tests before any code. You get a wall of red and no anchor to go back to. One test at a time. (Beck lists converting the whole test list into tests up front as a mistake.)
  2. Skipping the refactor step. You end up with code that merely passes. Fowler names skipping it as the most common way to undermine the practice.
  3. Steps that are too big. If one test needs hundreds of lines of new code, you are climbing without anchors. Write a smaller test.
  4. Testing private methods. They are details you want to stay free to change. Reaching in with reflection is a smell:
Method rule = ShippingCalculator.class.getDeclaredMethod("heavySurcharge", Order.class);
rule.setAccessible(true);

Test the behaviour through the public method instead.

Pitfalls: what TDD does not promise

  1. Treating TDD as a coverage target. Writing tests first promises no number, and a high number proves nothing about checks, as the JaCoCo lesson showed. Chase the checks, not the number.
  2. Tests coupled to the implementation. If a refactor that keeps behaviour breaks a test, that test knew too much about how. Assert what the code returns, not how it works inside.
  3. Mocking everything. A test made of mocks mostly checks your wiring. The Mockito lesson in this series shows when a test double helps, and when it hides the truth.

One caution: TDD fits best when you know the behaviour you want. When you are exploring an unfamiliar library, a throwaway experiment first is fine. Then delete it, and test-drive the real thing.

The tie back to PIT

Changing > to >= by hand, in the boundary cycle, was a mutant: the thing PIT plants for you (PIT’s conditionals-boundary mutator makes exactly this kind of change, and it is on by default). Tests that were seen failing first tend to kill mutants like it. That is a tendency, not a promise: only a mutation run can tell you.

The whole test class

All the pieces of the final suite together:

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class ShippingCalculatorTest {
    private ShippingCalculator calc;

    @BeforeEach
    void setUp() {
        calc = new ShippingCalculator();
    }

    private double costOf(double total, boolean express, double kg) {
        return calc.cost(new Order(total, express, kg));
    }

    @Test
    void heavyParcelPaysSurcharge() {
        assertEquals(10.0, costOf(120, false, 25), 0.001);
    }

    @Test
    void heavySmallOrderPaysFlatRatePlusSurcharge() {
        assertEquals(17.99, costOf(50, false, 25), 0.001);
    }

    @Test
    void exactlyTwentyKgPaysNoSurcharge() {
        assertEquals(7.99, costOf(50, false, 20), 0.001);
    }
}

Common questions

“Do I have to do TDD for everything?” No. It fits best when you know the behaviour you want, and it works well for logic with clear inputs and outputs. For exploration, spike first, then test-drive the real code.

“Isn’t faking it cheating?” It is a step, not the destination. The next test forces the real rule, and the fake never ships.

Recap

Write a test list. Red: one failing test. Green: the simplest code. Refactor, with the tests green. Repeat, in tiny steps.

Clip in often. Climb in small steps.

That completes the series: JUnit writes the check, JaCoCo shows what ran, PIT asks whether anything noticed, Mockito isolates the collaborators, and test-driven development puts the check first.

The five lessons of the testing series in order: JUnit 5 writes the check, JaCoCo shows what ran, PIT asks whether anything noticed, Mockito isolates collaborators, and test-driven development puts the check first. The five lessons of the testing series in order: JUnit 5 writes the check, JaCoCo shows what ran, PIT asks whether anything noticed, Mockito isolates collaborators, and test-driven development puts the check first.
The testing series: write the check, see what ran, see what was noticed, isolate collaborators, check first.

References