What is worth a test

A test that mocks the thing under test passes while the bug ships. Rules, boundaries, and asserting on behaviour rather than on which methods were called.

10 min read🧪 Testing Java Services

Coverage is a number you can raise without learning anything. This lesson is about the other question — which tests are worth having — and it starts with a test that passes against code that is wrong.

Two tests, one bug

A discount rule: over 5000 paise, take 10% off. Here is the implementation, with one wrong character:

Discount.javajava
public class Discount {
    public int apply(int amountPaise) {
        if (amountPaise >= 5000) return amountPaise - (amountPaise / 10);
        return amountPaise;
    }
}

>= where the rule says over. Now two tests of the class that uses it:

java
@Test
void testingTheMock() {
    Discount mock = mock(Discount.class);
    when(mock.apply(6000)).thenReturn(5400);
    Checkout checkout = new Checkout(mock);
    assertEquals(5400, checkout.total(6000));
    verify(mock).apply(6000);
}
 
@Test
void theBoundary() {
    Checkout checkout = new Checkout(new Discount());
    assertEquals(5000, checkout.total(5000), "the rule says OVER 5000");
}
plaintext
Tests run: 2, Failures: 1
 
CheckoutTest.theBoundary:23 the rule says OVER 5000 ==> expected: <5000> but was: <4500>

The first test passes. It stubs the discount to return 5400, then asserts it returned 5400, then verifies it was called. Every line is green and none of it touched the rule. It would keep passing if Discount.apply returned a random number.

The second test fails, and it fails on the one input where the rule is ambiguous in English and decisive in money.

Both count the same towards coverage. One of them is a liability, because it will keep passing while the bug ships.

The question to ask

Not "is this line covered". Ask: if this were wrong, would anything tell me?

That reframes it usefully, because it turns a test from a ritual into a claim. A test earns its place when it would fail for a reason somebody cares about.

Which gives a short list of what is worth testing:

  • Business rules. Anything a person could argue about. The discount threshold, the refund window, who may cancel an order.
  • Boundaries. Where a rule changes: exactly 5000, exactly 18, the last day of the month, the empty list, one element, the maximum.
  • Bugs you have already had. A test written from a real incident is the highest-value test in any suite, because it is proven to be able to fail.
  • The contract at your edges. What the API returns, what the database enforces.
  • Anything with an if whose branches mean different things to a customer.

And what is usually noise:

  • Getters, setters, toString, generated code. They are correct by construction; a test of them fails only when you change them on purpose.
  • A framework doing its job. You do not need a test that Spring injects a bean or that Jackson serialises a string.
  • Tests that restate the implementation. If the test is the code written twice, it fails whenever the code changes and never when it is wrong — which is worse than nothing, because it costs you every refactor.

Test behaviour, not structure

The single most useful discipline, and the one that decides whether a suite helps or hinders a year later.

java
// structure: fails when you rename or reorganise, passes when the rule is wrong
verify(repository).findById(42L);
verify(mapper).toDto(any());
 
// behaviour: fails when the answer is wrong, survives a rewrite
assertEquals(5000, checkout.total(5000));

A suite full of the first kind makes refactoring expensive — every internal change breaks tests that were not about that change — and teams respond by refactoring less. That is how a test suite ends up protecting the design it was supposed to let you improve.

verify is not banned. It is right when the interaction is the behaviour: an email must be sent exactly once, a payment must not be retried. Use it for effects the outside world can see, not for the route your code took to get there.

What "unit" means, and the argument about it

The word causes more confusion than it earns. Two readings:

  • A unit is a class. Everything it touches is mocked. Tests are fast and numerous, and they break on every refactor because they know the shape of the code.
  • A unit is a unit of behaviour — one class or five, whatever implements the rule, with only real boundaries stubbed. Tests are still fast, break far less on refactoring, and are what most people mean by a good unit test today.

The second is the more useful default, and the practical rule that follows is: mock at the boundary, use real objects inside it. A service, its validator and its mapper can all be real; the repository and the HTTP client are mocked.

Coverage is a floor, not a target

Coverage tells you what was executed, not what was checked. A test with no assertions covers everything it runs.

It is genuinely useful in one direction: a class at 0% is a class nobody tested, and that is worth knowing. The direction it fails in is being a target — a team asked for 80% writes tests of getters, because that is the cheapest way to raise the number.

Mutation testing answers the question coverage cannot. It changes your code — flips a > to >=, replaces a return with a constant — and asks whether any test noticed. A surviving mutant is a line that runs without being checked. pitest is the usual tool in Java, it is slow, and running it once on the module that carries your business rules is an education.

Under the hood: how a mutation testing tool actually decides a line is unchecked

pitest, the usual Java tool, works on already-compiled bytecode, not source. For each candidate line, it generates a mutant: a byte-for-byte copy of the class with one small, semantically loaded change made directly to the bytecode — a comparison flipped (> to >=), a method's return value replaced with a boundary constant, a call removed from a void method, a boolean negated. Mutating bytecode rather than re-invoking the compiler for every mutant is what makes the process tractable at all, and pitest further restricts itself to lines a coverage pass already showed some test reaches — mutating a line nothing executes would only ever produce a mutant nothing could possibly kill, telling you what the coverage report already told you.

For each mutant, pitest reruns the existing tests that the coverage pass showed reaching that line against that one mutated class and stops at the first failure — a "kill". If every test still passes against the mutated code, the mutant survives, meaning that line's behaviour, changed, made no test notice. This is a mechanical, exact version of the question this lesson opened with (if this were wrong, would anything tell me?) — except the tool actually makes the line wrong and checks, rather than asking you to imagine it. A high line-coverage percentage with many surviving mutants is the "green but for the wrong reason" trap the discount example at the top of this lesson demonstrates directly: coverage says the mutated line executed during some test; only mutation testing says whether any test's outcome actually depended on what that line does.

Try it yourself

Predict which test kills the mutant

Take this lesson's Discount.apply after the bug is fixed — the comparison is now amountPaise > 5000, so theBoundary passes — alongside its two tests: testingTheMock (which mocks Discount itself) and theBoundary (which uses the real Discount). (pitest has to start from a green suite; it refuses to run while a test is already failing.) If pitest mutated amountPaise > 5000 back to amountPaise >= 5000 and reran the tests: which test, if either, kills that mutant — and does the order the tests run in change the answer?

Why only a test that actually executes the line can ever kill it

theBoundary kills it; testingTheMock cannot kill it, in either order. testingTheMock never constructs or calls a real Discount — it mocks the class outright, so the mutated bytecode inside Discount.apply is never executed by that test at all, and a mutant inside code a test never runs cannot be detected by that test regardless of what the mutation changes. theBoundary constructs a real Discount and asserts checkout.total(5000) equals 5000; against the fixed > that assertion holds, and against the mutated >= the same input now takes the discounted branch and returns 4500, failing the assertion — a kill. It is the original bug, reintroduced, and the one test that pins the boundary catches it. Order is irrelevant because pitest judges each mutant afresh, running only the tests that cover the mutated line, with no state carried between one mutant's verdict and the next. This is the coverage argument from earlier in the lesson restated at the bytecode level: a test's reach determines whether it can catch anything at all, independent of what it happens to assert.

Misconceptions

  • "100% mutation score means the code has no bugs." It means every mutant pitest's operator set generated was caught by some test. Mutants are a fixed, mechanical family of small changes — an operator flipped, a call dropped — not every possible bug; a wrong constant chosen from the start, or a business rule never implemented at all, produces no mutant to kill and can carry a perfect score.
  • "Mutation testing can replace code review." It only ever runs against code that already exists, and only measures whether tests would catch a small mechanical change to it. It says nothing about a requirement nobody wrote, which review — and this lesson's "if this were wrong, would anything tell me" question, asked by a person — is still the tool for.

Sources

  • The pitest documentation (Java mutation testing).
  • Martin Fowler, "TestCoverage" (bliki) — coverage as a floor, not a target.
  • DeMillo, Lipton and Sayward, "Hints on Test Data Selection: Help for the Practicing Programmer" (1978) — the foundational mutation-testing paper.
Progress is saved on this device and to your account when signed in.