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 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 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.
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) {}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:
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.
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.
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.
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.
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 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.
| Cycle | Test | Red | Green |
|---|---|---|---|
| 1 | heavy parcel, free shipping | expected: <10.0> but was: <0.0> | fake: return 10 |
| 2 | heavy small order | expected: <17.99> but was: <10.0> | real rule: shipping += 10, then refactor |
| 3 | exactly 20 kg | green at once; red after flipping > to >= | flip back |
Method rule = ShippingCalculator.class.getDeclaredMethod("heavySurcharge", Order.class);
rule.setAccessible(true);Test the behaviour through the public method instead.
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.
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.
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);
}
}“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.
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.