# Test-Driven DevelopmentWrite 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.

{{< lesson-video youtube="-n1qN4Gu4lI" title="Test-Driven Development" >}}

This is the last lesson of a series on testing in Java. It builds on [unit testing with JUnit 5](/testing/junit5-unit-testing/),
[code coverage with JaCoCo](/testing/jacoco-code-coverage/),
[mutation testing with PIT](/testing/pit-mutation-testing/) and [test doubles with Mockito](/testing/mockito-test-doubles/).
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.

```mermaid {alt="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." caption="The climb, mapped onto the lesson."}
flowchart LR
  A1["passing test"] --> B1["an anchor"]
  A2["small step"] --> B2["a short climb"]
  A3["red test"] --> B3["a fall to the last anchor"]
  A4["big step"] --> B4["a long climb, no anchors"]
  class A1,A2,A3,A4 c4
  class B1 good
  class B2 c1
  class B3 bad
  class B4 warn
```

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

```mermaid {alt="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." caption="Three stops, round and round."}
flowchart LR
  R["red<br/>one failing test"] --> G["green<br/>simplest code<br/>that passes"]
  G --> F["refactor<br/>clean up,<br/>still green"]
  F -->|next list item| R
  class R bad
  class G good
  class F c4
```

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:

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

## The test list

Here is the calculator as it stands:

```java
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.

```java
@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:

```text
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.

```java
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.

```java
@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:

```text
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:

```java
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.

```mermaid {alt="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)." caption="Pick a step size to match your confidence."}
flowchart TD
  Q{"is the rule obvious?"} -->|yes| T["type it"]
  Q -->|no| F["fake it:<br/>return a constant"]
  F --> X["add a second example<br/>that breaks the constant"]
  X --> R["the real rule appears"]
  class T good
  class F warn
  class X bad
  class R good
```

## Refactor with the tests green

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

```java
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:

```java
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:

```java
@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:

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

Run it again:

```text
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 |

## 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:

```java
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

5. **Treating TDD as a coverage target.** Writing tests first promises no number, and a high number
   proves nothing about checks, as the [JaCoCo lesson](/testing/jacoco-code-coverage/) showed.
   Chase the checks, not the number.
6. **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.
7. **Mocking everything.** A test made of mocks mostly checks your wiring. The [Mockito lesson](/testing/mockito-test-doubles/) 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](/testing/pit-mutation-testing/) 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:

```java
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.

```mermaid {alt="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." caption="The testing series: write the check, see what ran, see what was noticed, isolate collaborators, check first."}
flowchart TD
  A["JUnit 5"] --> B["JaCoCo"]
  B --> C["PIT"]
  C --> D["Mockito"]
  D --> E["TDD"]
  class A,B,C,D c1
  class E hl
```

## References

- Kent Beck, [Canon TDD](https://newsletter.kentbeck.com/p/canon-tdd) and *Test-Driven Development: By Example* (fake implementation and triangulation, from the chapter ["Equality for All"](https://informit.com/articles/article.aspx?p=30641))
- Martin Fowler, [Test-Driven Development](https://martinfowler.com/bliki/TestDrivenDevelopment.html)
- Robert C. Martin, [The Cycles of TDD](https://blog.cleancoder.com/uncle-bob/2014/12/17/TheCyclesOfTDD.html) (the three rules)
- [Test-driven development](https://en.wikipedia.org/wiki/Test-driven_development) (Wikipedia)
- [PIT mutators](https://pitest.org/quickstart/mutators/)
