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 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.
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.
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 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 lab | In your tests |
|---|---|
| crash-test dummy | test double |
| a person | a real collaborator |
| sensors | recorded calls |
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.
| Kind | What it does | In our example |
|---|---|---|
| Dummy | is passed around but never used; it only fills a parameter list | a Notifier that does nothing |
| Stub | gives canned answers to the calls the test makes | CarrierRates always answering 7.99 |
| Spy | a stub that also records how it was called | a real object, wrapped so its calls are recorded |
| Mock | is set up with expectations about the calls it should receive | a Notifier we expect to hear freeShipping(order) |
| Fake | really works, with a shortcut that makes it unfit for production | an 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.
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 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.
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.
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.
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.
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 testing | Interaction testing | |
|---|---|---|
| Asks | what came back? | which calls were made? |
| In our example | assertEquals(7.99, service.cost(...), 0.001) | verify(notifier).freeShipping(order) |
| Survives refactoring | yes | only while the calls stay the same |
| Use it | by default | when 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.
verify only when the call is the point.// 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);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.assertEquals(7.99, service.cost(order, "UPS"), 0.001);
verify(rates).baseRate("UPS"); // the answer already proves itCarrierRates 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 matchersmockStatic 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.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 nothingMock-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.
Mock the edge. Test the logic.
A double stands in, so your test can measure what the code really does.
Mockito Javadoc (argument matchers, verify, spies, inline mock maker, mockStatic),
ArgumentCaptor,
InjectMocks,
MockitoExtension