Software Testing & Quality

Test-Driven Development in Java: A Worked Kata and an Honest Appraisal

Intermediate8 min readUpdated

TDD is a design discipline that happens to leave tests behind. This guide walks a complete problem from the first failing assertion to a refactored design, then examines what the practice actually does to code structure, how to handle collaborators, where it works badly, and what the evidence for it really shows.

What you will learn

  • Run the red-green-refactor loop with the discipline that makes it useful
  • Grow a small design from tests, choosing the next test deliberately
  • Choose between outside-in and inside-out for a given feature
  • Recognise the situations where test-first is a poor fit and say why
  • Answer the standard objections to TDD with something better than enthusiasm

Test-driven development is easy to describe and hard to do well. You write a test that fails, write the least code that makes it pass, then improve the design while the test keeps passing. Everything interesting about the practice lies in what that constraint does to you: you cannot write code that is impossible to call, you cannot invent an abstraction before you have a use for it, and you always know whether the thing you just wrote works.

It is also frequently oversold. TDD is not a testing strategy — a suite grown from unit-level TDD covers very little integration risk — and it is not a substitute for thinking about design. What it reliably provides is a tight feedback loop and code that is easy to instantiate, and those two things turn out to matter a great deal. This guide works a full example, then looks honestly at where the practice earns its keep and where it does not.

The loop, precisely

Red. Write one test for behaviour that does not exist. Run it. It must fail, and it must fail for the reason you expect — a test that fails because of a typo in the setup teaches you nothing. A test that passes immediately means you have not identified new behaviour.

Green. Write the simplest code that makes the test pass. "Simplest" is meant literally, including returning a constant. This feels absurd the first time and is the mechanism by which the next test is forced to be about something real.

Refactor. With every test green, improve the structure: remove duplication, rename, extract, collapse. This is the step people skip, and skipping it turns TDD into a way of producing badly designed code with good test coverage.

Two habits make the loop work. Keep each cycle to a couple of minutes — if you have been red for fifteen minutes, the step was too big; revert and take a smaller one. And treat the test code as production code: it will be read far more often than it is written.

A kata, from nothing to a design

The problem: a RomanNumerals converter, int to String, for values from 1 to 3999. It is small enough to show in full and rich enough to have a real design decision in the middle.

The first test is the smallest possible statement of intent.

class RomanNumeralsTest {

    @Test
    void one() {
        assertThat(RomanNumerals.of(1)).isEqualTo("I");
    }
}

It does not compile, which counts as red. The simplest thing that makes it green:

public final class RomanNumerals {
    public static String of(int value) {
        return "I";
    }
}

Now a second test forces the code to distinguish two cases.

@Test
void two() {
    assertThat(RomanNumerals.of(2)).isEqualTo("II");
}

The obvious fix — an if — is worse than the general one, and this is the moment where the design appears:

public static String of(int value) {
    return "I".repeat(value);
}

That passes 1, 2 and 3, and fails at 4. Rather than write four separate tests, express the cases as a table, which is where a parameterised test belongs:

@ParameterizedTest(name = "{0} -> {1}")
@CsvSource({"1,I", "3,III", "4,IV", "9,IX", "14,XIV", "40,XL", "90,XC",
            "400,CD", "900,CM", "1994,MCMXCIV", "3999,MMMCMXCIX"})
void converts(int value, String expected) {
    assertThat(RomanNumerals.of(value)).isEqualTo(expected);
}

Adding 4,IV alone breaks repeat. The temptation is a chain of conditionals; the refactoring step is what stops that. The insight — that the subtractive forms IV, IX, XL are simply extra symbols in an ordered table — arrives because the duplication in the conditionals makes it visible:

public final class RomanNumerals {

    private record Symbol(int value, String glyph) {}

    private static final List<Symbol> SYMBOLS = List.of(
            new Symbol(1000, "M"), new Symbol(900, "CM"), new Symbol(500, "D"), new Symbol(400, "CD"),
            new Symbol(100, "C"),  new Symbol(90, "XC"),  new Symbol(50, "L"),  new Symbol(40, "XL"),
            new Symbol(10, "X"),   new Symbol(9, "IX"),   new Symbol(5, "V"),   new Symbol(4, "IV"),
            new Symbol(1, "I"));

    private RomanNumerals() {}

    public static String of(int value) {
        if (value < 1 || value > 3999) {
            throw new IllegalArgumentException("Roman numerals cover 1..3999, got " + value);
        }
        StringBuilder out = new StringBuilder();
        int remaining = value;
        for (Symbol symbol : SYMBOLS) {
            while (remaining >= symbol.value()) {
                out.append(symbol.glyph());
                remaining -= symbol.value();
            }
        }
        return out.toString();
    }
}

The guard clause came from its own red test, written after the table was green:

@ParameterizedTest
@ValueSource(ints = {0, -1, 4000, Integer.MAX_VALUE})
void rejectsValuesOutsideTheRange(int value) {
    assertThatThrownBy(() -> RomanNumerals.of(value))
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining("1..3999");
}

Notice what the sequence produced. The table is not an implementation that happened to work; it is the structure the tests pushed towards, because every conditional the tests forced in was duplication of the same shape. Notice also what was not built: no RomanNumeralFactory, no strategy interface, no configuration. Nothing demanded them.

What the tests do to the design

TDD applies four kinds of pressure, and they are the actual product of the practice.

Everything must be constructible. A class whose constructor reads a static singleton, opens a connection or launches a thread pool cannot be built in a test cheaply. Under TDD you feel that in the first minute and pass the dependency in instead, which is the same conclusion dependency injection reaches from the other direction.

Everything must be observable. If the only effect of a method is a log line or a private field mutation, the test cannot assert anything. That pressure pushes towards returning values rather than mutating hidden state, and towards side effects concentrated at a few explicit places.

Units stay small. A method with eight branches needs eight or more tests with elaborate setup. The pain arrives before the method ships, not during a review three weeks later.

Abstractions arrive late. The refactoring step introduces an interface when a second implementation exists, not when someone anticipates one. Speculative generality is the most expensive kind of waste in a codebase, and test-first makes it awkward to create.

None of this is automatic. A team can produce heavily tested procedural code with a god service and a hundred mocks. The discipline creates the pressure; the designer still has to respond to it.

Outside-in and inside-out

There are two ways to enter a feature, and they suit different situations.

Inside-out (sometimes called classicist) starts with the domain object at the centre — the calculation, the state machine, the parsing rule — and works outwards to the controller. Collaborators are real objects wherever they are cheap. The tests are robust because they assert on values rather than interactions, and refactoring rarely breaks them. The risk is that you build a beautifully tested core that does not fit the API you eventually need.

Outside-in (mockist, London school) starts at the boundary: an acceptance test for the user-visible behaviour, then a test for the controller with a mocked service, then the service with a mocked repository, discovering each interface at the moment it is needed. The design comes out cohesive because every collaborator was invented to satisfy a caller. The cost is tests coupled to interactions: change how a service talks to its repository and the test fails even though behaviour is identical.

In practice most experienced teams run outside-in at the feature level to discover the shape, then inside-out within each unit that contains real logic. The BDD guide describes the outermost loop of this — a failing scenario that stays red while several unit-level cycles run inside it.

Collaborators, without drowning in mocks

Test-first work stalls the moment the object under test needs something slow. Three responses, in order of preference:

  1. Push the dependency out. If a method needs the current date, take a Clock. If it needs a total from a repository, take the total as a parameter and let the caller fetch it. Functions of their arguments are trivially testable.
  2. Use a fake. An in-memory implementation of a small repository interface makes a dozen tests read like ordinary code and catches ordering bugs that stubs cannot.
  3. Mock, sparingly. Reserve mocks for genuine boundaries — a payment gateway, a mail sender — where the interaction is the behaviour worth asserting.

When a test needs more than about three stubbed calls to run, the design is usually asking for a smaller object. That signal is one of the more reliable pieces of feedback the practice provides.

Where test-first is hard

Legacy code. You cannot drive code you cannot instantiate. Wrap the existing behaviour in a coarse characterisation test first — record what it currently does, correct or not — then introduce a seam and work test-first inside it.

Algorithms with a hard-to-guess implementation. For a numerical routine or a graph algorithm, small tests will not lead you to the right approach; the algorithm has to be understood first. Test-first still helps, but as a way of pinning down the specification and the edge cases, not of discovering the method.

User interfaces. Layout and interaction are judged by eye. Drive the presentation logic test-first and keep the rendering layer thin enough that its own correctness is obvious.

Exploration. When you are learning an unfamiliar API, write a spike with no tests, learn what you needed, delete it, and start again test-first. Trying to TDD through unfamiliar territory produces tests for guesses.

Highly concurrent code. A test that passes ninety-nine times out of a hundred is worse than no test. Concurrency needs deterministic designs, stress runs and specialised tools rather than the ordinary loop.

The objections, answered honestly

"It doubles the amount of code." Roughly, yes — test code is often comparable in size to production code. The question is whether that code pays for itself in reduced debugging, safer refactoring and living documentation. On a codebase that will be maintained for years, it usually does; on a script that runs once, it does not.

"The evidence is not conclusive." Correct. Empirical studies of test-first versus test-after report effects ranging from meaningful defect reduction to no significant difference, with effort results equally mixed. Much of the measured benefit may come from writing small units and many tests rather than from the ordering. That is a reason to be modest about claims, not a reason to skip testing.

"My tests break every time I refactor." Then the tests are asserting on structure rather than behaviour — usually too many verify calls, or tests written against private methods made package-visible. Assert on what a caller can observe.

"We do not have time." The time is spent either way; the choice is between writing tests and manually re-checking behaviour by hand every time something changes. The honest version of this objection is usually about a deadline for a prototype, and for a genuine throwaway prototype it is a reasonable trade — as long as the prototype is actually thrown away.

"Coverage is already high, so we are fine." Coverage measures execution, not assertion. A suite can execute every line while asserting almost nothing. What TDD produces is not coverage but the guarantee that every behaviour had a test that failed for its absence, which is a much stronger property — and one the automation strategy guide argues should be preferred over a coverage target.

Key takeaways

  • The loop is red, green, refactor — and the refactor step is the one that turns a test suite into a design practice rather than a safety net.
  • Write the simplest code that passes, including constants; the next test is what forces generality, and the duplication it creates is what reveals the right structure.
  • Test-first pressure makes code constructible, observable and small, and delays abstractions until a second use case justifies them.
  • Choose outside-in to discover interfaces at a feature boundary and inside-out for units with real logic; most teams use both in the same feature.
  • Push dependencies out, prefer fakes to mocks, and treat "this test needs four stubs" as a design smell rather than a setup problem.
  • Be honest about the limits: legacy code needs seams first, algorithms need understanding first, and the empirical evidence supports modest claims rather than grand ones.

Sources and further reading

Frequently asked questions

Is TDD slower than writing the code first?
Per feature, writing the first version is usually a little slower, because you pay for the tests up front instead of never. Over a codebase's life the comparison changes: debugging time drops sharply because failures surface within seconds of being introduced, and refactoring stops being risky. Controlled studies show mixed effect sizes on defect density and effort, so treat claims of dramatic speed-up with scepticism and judge it on your own codebase.
Do I have to write a test before every single line?
No. The discipline is that no production behaviour is added without a failing test demanding it — which is not the same as one test per line. Exploratory work, spikes and prototypes are better done without tests and then thrown away or rewritten test-first. Configuration, generated code and trivial delegation rarely benefit. Being dogmatic about it is how teams end up writing tests for getters.
What is the difference between the London and Chicago schools?
The London (mockist, outside-in) school starts at the system boundary, mocks each collaborator as it is discovered and drives the design top-down through interfaces. The Chicago (classicist, inside-out) school starts with the domain objects, uses real collaborators wherever they are cheap, and grows outward. London gives faster feedback on structure and more brittle tests; Chicago gives more robust tests and later discovery of the interfaces. Most teams mix them.
Can TDD be applied to legacy code with no tests?
Not directly, because legacy code usually cannot be instantiated in a test without dragging in half the application. The standard route is to first add a characterisation test around the existing behaviour at whatever coarse boundary is reachable, use it as a safety net to introduce a seam — extract an interface, add a constructor parameter, break a static dependency — and then work test-first inside that seam. The net grows one crack at a time.