Test Doubles with Mockito

November 27, 202611 minutes

Part 4 of 5

A service that calls a remote carrier is slow and flaky to test. Learn the five kinds of test double, how Mockito builds them, state versus interaction testing, and what not to mock.

Our shipping calculator has grown up. A shipping service now asks a remote carrier for the base rate, and it tells a notifier when the shipping is free. Now try to test it. Every test calls the real carrier over the network. That is slow, it fails at random, and you can’t make the carrier go down on purpose. And a test shouldn’t message a real customer either. What we need are stand-ins that we control. Those stand-ins are called test doubles, and Mockito is the library that builds them.

Prefer to watch? The narrated video covers the same lesson (about ten minutes). The article follows it section by section, with diagrams, the Maven equivalent and a little extra depth. It builds on the series’ lessons on code coverage and mutation testing, and pairs with the lessons on JUnit 5 and test-driven development.

The calculator grows up

The running example is the shipping calculator from the earlier lessons, grown into a service. An Order is still record Order(double total, boolean express). The service has two collaborators: a CarrierRates that asks a remote API for the base rate, and a Notifier that tells the customer when shipping is free. The tests that follow use these numbers: an order of 50 pays the carrier’s rate (7.99 for UPS), and an order of 120 is at least 100, so it ships free and the notifier is told once.

Class diagram: ShippingService asks the CarrierRates interface for a rate and tells the Notifier interface when shipping is free. In production the implementations are a remote carrier client and an email notifier; in tests they are a hand-written fake, a Mockito stub and a Mockito mock. Class diagram: ShippingService asks the CarrierRates interface for a rate and tells the Notifier interface when shipping is free. In production the implementations are a remote carrier client and an email notifier; in tests they are a hand-written fake, a Mockito stub and a Mockito mock.
The service depends on two interfaces; production and tests plug in different implementations.

Testing this with the real implementations is slow, it fails at random, it can’t simulate an outage on demand, and it would message real customers.

Dependencies come in through the constructor

First, the two collaborators, as plain interfaces. One answers a base rate. The other announces free shipping.

public interface CarrierRates {
    double baseRate(String carrier);
}

public interface Notifier {
    void freeShipping(Order order);
}

And here is the service. It doesn’t create the carrier or the notifier. Both arrive through the constructor.

public class ShippingService {
    private final CarrierRates rates;
    private final Notifier notifier;

    public ShippingService(CarrierRates rates, Notifier notifier) {
        this.rates = rates;
        this.notifier = notifier;
    }

    public double cost(Order order, String carrier) {
        if (order.total() >= 100) {
            notifier.freeShipping(order);
            return 0;
        }
        double shipping = rates.baseRate(carrier);
        if (order.express()) {
            shipping += 15;
        }
        return shipping;
    }
}

Because they come from outside, a test can hand in anything that fits the interface. That one design choice makes every trick in this lesson possible.

A crash-test dummy

A crash-test dummy stands in for a person. It sits in the car and takes the crash, and nobody drives one to work. It is built to be measured: sensors record what happened to it, and the engineers read those records afterwards.

A test double is the same idea for code. It stands in for a real collaborator, the test decides how it behaves, and it can record what it was asked.

In the crash labIn your tests
crash-test dummytest double
a persona real collaborator
sensorsrecorded calls

Five kinds of test double

Gerard Meszaros named the kinds, and Martin Fowler’s article Mocks Aren’t Stubs explains them. Test double is the umbrella term for any pretend object used in place of a real one.

Taxonomy of test doubles: test double is the umbrella over dummy (never used), stub (canned answers), fake (works, with a shortcut) and mock (expectations about calls); a spy is a stub that also records its calls. Taxonomy of test doubles: test double is the umbrella over dummy (never used), stub (canned answers), fake (works, with a shortcut) and mock (expectations about calls); a spy is a stub that also records its calls.
Five kinds under one umbrella.
KindWhat it doesIn our example
Dummyis passed around but never used; it only fills a parameter lista Notifier that does nothing
Stubgives canned answers to the calls the test makesCarrierRates always answering 7.99
Spya stub that also records how it was calleda real object, wrapped so its calls are recorded
Mockis set up with expectations about the calls it should receivea Notifier we expect to hear freeShipping(order)
Fakereally works, with a shortcut that makes it unfit for productionan in-memory rates table instead of a remote service

In Mockito, one object can play several of these roles. Stub it with when(...), and it acts as a stub. Verify its calls with verify(...), and it acts as a mock. The names describe the job, not the class.

A hand-written fake

Start with no library at all. Write a fake carrier: a class that implements the interface and looks the rates up in a small table.

class FakeCarrierRates implements CarrierRates {
    private final Map<String, Double> table = Map.of("UPS", 7.99, "DHL", 11.5);

    @Override
    public double baseRate(String carrier) {
        return table.get(carrier);
    }
}

Now the test hands the fake to the service. The notifier doesn’t matter here, so a lambda that does nothing will do. That is a dummy. (Notifier has a single method, so a lambda can implement it.)

@Test
void smallOrderPaysTheCarrierRate() {
    Notifier dummy = order -> { };
    ShippingService service =
            new ShippingService(new FakeCarrierRates(), dummy);

    assertEquals(7.99, service.cost(new Order(50, false), "UPS"), 0.001);
}

No network, no waiting, and the same answer every time. But each new situation needs another class, and a carrier that is down needs a fake that throws. A fake is real code, so many tests can share it. It earns its place when several tests need the same working behaviour.

Mockito: doubles on demand

Mockito builds doubles for you. Call mock with an interface, and you get an object that has that interface and does nothing. It doesn’t fail when you call it: an unstubbed method just returns a default, which is zero for a number, empty for a collection, and otherwise null. Then teach it. When the carrier is asked for the UPS rate, then return the flat rate. Now it is a stub: a canned answer.

@Test
void smallOrderPaysTheCarrierRate() {
    CarrierRates rates = mock(CarrierRates.class);
    when(rates.baseRate("UPS")).thenReturn(7.99);
    Notifier notifier = mock(Notifier.class);
    ShippingService service = new ShippingService(rates, notifier);

    assertEquals(7.99, service.cost(new Order(50, false), "UPS"), 0.001);
}

The test then checks what the service returned. That is state testing: we assert on the result, not on how it got there.

Sequence diagram with four participants. The test calls ShippingService.cost for an order of 50; the service asks the stubbed CarrierRates for baseRate UPS and gets 7.99, then returns 7.99. The test then calls cost for an order of 120; the service tells the mocked Notifier freeShipping, returns 0, and the test verifies the call on the Notifier. Sequence diagram with four participants. The test calls ShippingService.cost for an order of 50; the service asks the stubbed CarrierRates for baseRate UPS and gets 7.99, then returns 7.99. The test then calls cost for an order of 120; the service tells the mocked Notifier freeShipping, returns 0, and the test verifies the call on the Notifier.
A stubbed answer and a verified notification.

A stub can also fail on purpose. thenThrow makes the carrier raise an exception, so we can finally test an outage. Our service lets that exception reach the caller, and the test says so with assertThrows.

@Test
void carrierOutageReachesTheCaller() {
    CarrierRates rates = mock(CarrierRates.class);
    when(rates.baseRate("UPS"))
            .thenThrow(new IllegalStateException("carrier down"));
    Notifier notifier = mock(Notifier.class);
    ShippingService service = new ShippingService(rates, notifier);

    assertThrows(IllegalStateException.class,
            () -> service.cost(new Order(50, false), "UPS"), 0.001);
}

Mockito also has spies. A spy wraps a real object, so the real methods run unless you stub them. The Mockito documentation notes that overusing spies hints at design smells, so reach for them last.

Less boilerplate: the Mockito extension

Building mocks by hand in every test gets repetitive. With the Mockito extension, you mark fields instead. Extend with MockitoExtension, mark the doubles with @Mock, and mark the service with @InjectMocks. Mockito builds the service through its constructor (it tries constructor injection first, then setters, then fields).

@ExtendWith(MockitoExtension.class)
class ShippingServiceTest {
    @Mock CarrierRates rates;
    @Mock Notifier notifier;
    @InjectMocks ShippingService service;

    @Test
    void smallOrderPaysTheCarrierRate() {
        when(rates.baseRate("UPS")).thenReturn(7.99);

        assertEquals(7.99, service.cost(new Order(50, false), "UPS"), 0.001);
    }
}

This extension also turns on strict stubs. A stub the test never uses fails the test, with an UnnecessaryStubbingException. That keeps stubbing minimal. In the test below, the DHL stub is never realised, because the service is called with UPS, so the test fails.

@Test
void smallOrderPaysTheCarrierRate() {
    when(rates.baseRate("UPS")).thenReturn(7.99);
    when(rates.baseRate("DHL")).thenReturn(11.5); // never used

    assertEquals(7.99, service.cost(new Order(50, false), "UPS"), 0.001);
}

The setup is two Gradle lines: the core library (mockito-core), and the JUnit Jupiter artifact (mockito-junit-jupiter), next to JUnit Jupiter itself.

dependencies {
    testImplementation("org.mockito:mockito-core:5.25.0")
    testImplementation("org.mockito:mockito-junit-jupiter:5.25.0")
}

tasks.test {
    useJUnitPlatform()
}

Maven takes the same two artifacts, as test-scoped dependencies:

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>5.25.0</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-junit-jupiter</artifactId>
  <version>5.25.0</version>
  <scope>test</scope>
</dependency>

Mockito 5 uses its inline mock maker by default. On Java 21 and later the JVM restricts attaching agents to itself, so the inline mock maker may need explicit instrumentation setup, and the JVM always shows a warning; the Mockito documentation describes the setup.

Verifying calls

Sometimes the result is a call. When shipping is free, the notifier has to hear about it. There is no return value to check, so we verify the call. verify(notifier).freeShipping(order) reads as “verify, then the notifier, then the call”, and by default Mockito expects exactly one. The opposite matters too: for a paid order, verify(notifier, never()) checks that the notifier was not told.

@Test
void freeShippingTellsTheCustomer() {
    Order order = new Order(120, false);

    service.cost(order, "UPS");

    verify(notifier).freeShipping(order);
}

@Test
void paidShippingStaysQuiet() {
    service.cost(new Order(50, false), "UPS");

    verify(notifier, never()).freeShipping(any());
}

To check what was sent, not only that something was, use an ArgumentCaptor. Capture the order, then assert on it as usual. (Use the captor inside verify; the Mockito documentation recommends it for verification, not for stubbing.)

@Test
void notifiesWithTheSameOrder() {
    ArgumentCaptor<Order> sent = ArgumentCaptor.forClass(Order.class);

    service.cost(new Order(120, false), "UPS");

    verify(notifier).freeShipping(sent.capture());
    assertEquals(120.0, sent.getValue().total(), 0.001);
}

One warning from the Mockito docs: don’t call verifyNoMoreInteractions in every test. It is a handy tool for when it matters, not a habit.

State or interaction?

There are two ways to check a test. State testing asks what the code returned. Interaction testing asks which calls it made. Prefer state where you can. A returned cost survives refactoring: the service can ask the carrier in any order, and the test still passes. Verify a call only when the call is the behaviour. Telling the customer is a side effect with no return value, so that is the one to verify.

State testingInteraction testing
Askswhat came back?which calls were made?
In our exampleassertEquals(7.99, service.cost(...), 0.001)verify(notifier).freeShipping(order)
Survives refactoringyesonly while the calls stay the same
Use itby defaultwhen the call is the behaviour

Fowler calls these two styles classical and mockist. A classical tester uses real objects where possible, and a double only when the real one is awkward. A mockist uses mocks for any object with interesting behaviour, and verifies behaviour. This lesson leans classical.

Best practices

  1. Inject your dependencies. Constructor injection is what lets a test swap them.
  2. Use real objects for value objects and your own simple code. A new order is one line, so don’t mock it. Your own plain classes are the same.
  3. Mock at the boundary. The network, the clock and email are slow, random, or have side effects. Mock the roles you can name, and wrap the rest.
  4. Give each test one reason to fail. One behaviour, a few lines, and a name that says which. Then a failure tells you what broke before you open the code.
  5. Check outcomes before interactions. Reach for verify only when the call is the point.
  6. Stub only what the test needs. Strict stubs will tell you when you don’t, and a short test reads like a sentence.
Decision flowchart: is the collaborator slow, random or does it have side effects? If yes, use a double (a fake or a mock). If no, is it a value object or your own simple code? If yes, use the real one. If no, does the test need the whole chain to work? If yes, write an integration test with the real thing; otherwise use a double. Decision flowchart: is the collaborator slow, random or does it have side effects? If yes, use a double (a fake or a mock). If no, is it a value object or your own simple code? If yes, use the real one. If no, does the test need the whole chain to work? If yes, write an integration test with the real thing; otherwise use a double.
Mock or not?

Pitfalls

  1. Over-mocking. When every collaborator is a mock, the test repeats the implementation, and it breaks on every refactor even though the behaviour is the same.
  2. Mocking value objects. Mockito 5 can mock a final class like our order (the inline mock maker is the default since 5.0.0), but a real one takes a single line. The Mockito wiki says that a painful constructor is not a reason to mock; use a builder or a factory method instead.
// harder than it needs to be
Order order = mock(Order.class);
when(order.total()).thenReturn(50.0);

// one line, and real
Order order = new Order(50, false);
  1. Mocking types you don’t own. A third-party client can change its behaviour, and your mock will never notice. Wrap it in your own small interface, like our CarrierRates, and mock that. That is the adapter idea: your code depends on an interface you control, and one small class translates to the library. The Mockito wiki recommends exactly this, with an integration test for the wrapper.
  2. Verifying everything. Checking every call pins down the implementation, so a harmless reorder fails the test.
assertEquals(7.99, service.cost(order, "UPS"), 0.001);
verify(rates).baseRate("UPS"); // the answer already proves it
  1. Mixing raw values with matchers. If one argument uses a matcher, all of them must, or Mockito throws an exception (the same rule applies to stubbing). Say CarrierRates also had a quote(String carrier, boolean express) method:
// say CarrierRates also had quote(String, boolean)
verify(rates).quote(anyString(), true);     // wrong
verify(rates).quote(anyString(), eq(true)); // right: all matchers
  1. Mocking static or final code. Mockito 5’s default mock maker can do it: final classes and methods can be mocked, and mockStatic mocks static methods inside a try-with-resources block. But needing it is often a design smell. Inject a Clock instead of mocking a static call to the time.
  2. Stubbing the method you are testing. The test then checks the stub, and the real code never runs.
ShippingService service = mock(ShippingService.class); // under test
Order order = new Order(50, false);
when(service.cost(order, "UPS")).thenReturn(7.99);

assertEquals(7.99, service.cost(order, "UPS"), 0.001); // proves nothing

Tie-ins, when not to use doubles

Mock-heavy tests can show high coverage while killing few mutants, because nothing real gets checked. Coverage and mutation testing show you when that happens. In test-driven development, doubles let you write the test before the real carrier exists.

When not to use a double? For pure functions and value objects, just call them. For an integration test, use the real thing.

Recap

Mock the edge. Test the logic.

A double stands in, so your test can measure what the code really does.

References