# Test Doubles with MockitoA 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](/testing/jacoco-code-coverage/) and
[mutation testing](/testing/pit-mutation-testing/), and pairs with the lessons on [JUnit 5](/testing/junit5-unit-testing/) and
[test-driven development](/testing/test-driven-development/).

{{< lesson-video youtube="nsUMw7ypcXA" title="Test Doubles with Mockito" >}}

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

```mermaid {alt="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." caption="The service depends on two interfaces; production and tests plug in different implementations."}
classDiagram
  class ShippingService {
    +cost(order, carrier)
  }
  class CarrierRates {
    <<interface>>
    +baseRate(carrier)
  }
  class Notifier {
    <<interface>>
    +freeShipping(order)
  }
  class RemoteCarrierRates
  class FakeCarrierRates
  class EmailNotifier
  class MockedNotifier
  ShippingService --> CarrierRates : asks
  ShippingService --> Notifier : tells
  CarrierRates <|.. RemoteCarrierRates
  CarrierRates <|.. FakeCarrierRates
  Notifier <|.. EmailNotifier
  Notifier <|.. MockedNotifier
```

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.

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

```java
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 lab | In your tests |
|---|---|
| crash-test dummy | test double |
| a person | a real collaborator |
| sensors | recorded calls |

## Five kinds of test double

Gerard Meszaros named the kinds, and Martin Fowler's article
[Mocks Aren't Stubs](https://martinfowler.com/articles/mocksArentStubs.html) explains them. **Test
double** is the umbrella term for any pretend object used in place of a real one.

```mermaid {alt="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." caption="Five kinds under one umbrella."}
flowchart TD
  TD["test double"] --> D["dummy<br/>never used"]
  TD --> S["stub<br/>canned answers"]
  TD --> F["fake<br/>works, with a shortcut"]
  TD --> M["mock<br/>expectations about calls"]
  S --> SP["spy<br/>a stub that<br/>records its calls"]
  class TD hl
  class D c4
  class S good
  class F warn
  class M c1
  class SP c5
```

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

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

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

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

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

```mermaid {alt="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." caption="A stubbed answer and a verified notification."}
sequenceDiagram
  participant T as Test
  participant S as ShippingService
  participant R as CarrierRates stub
  participant N as Notifier mock
  T->>S: cost(order of 50, UPS)
  S->>R: baseRate(UPS)
  R-->>S: 7.99 (stubbed)
  S-->>T: 7.99
  T->>S: cost(order of 120, UPS)
  S->>N: freeShipping(order)
  S-->>T: 0
  T->>N: verify freeShipping(order)
```

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

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

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

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

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

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

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

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

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

```mermaid {alt="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." caption="Mock or not?"}
flowchart TD
  Q["a collaborator<br/>in the test"] --> A{"slow, random or<br/>side effects?"}
  A -->|yes| B["use a double<br/>(fake or mock)"]
  A -->|no| C{"value object or your<br/>own simple code?"}
  C -->|yes| D["use the real one"]
  C -->|no| E{"does the test need<br/>the whole chain?"}
  E -->|yes| F["integration test:<br/>the real thing"]
  E -->|no| B
  class B c5
  class D good
  class F c4
```

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

```java
// 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);
```

3. **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](/patterns/adapter-pattern/): 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.
4. **Verifying everything.** Checking every call pins down the implementation, so a harmless
   reorder fails the test.

```java
assertEquals(7.99, service.cost(order, "UPS"), 0.001);
verify(rates).baseRate("UPS"); // the answer already proves it
```

5. **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:

```java
// say CarrierRates also had quote(String, boolean)
verify(rates).quote(anyString(), true);     // wrong
verify(rates).quote(anyString(), eq(true)); // right: all matchers
```

6. **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.
7. **Stubbing the method you are testing.** The test then checks the stub, and the real code never
   runs.

```java
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](/testing/jacoco-code-coverage/) and
[mutation testing](/testing/pit-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

- Martin Fowler, [Mocks Aren't Stubs](https://martinfowler.com/articles/mocksArentStubs.html) (the test double vocabulary and classical vs mockist testing)
- Mockito: [`Mockito` Javadoc](https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html) (argument matchers, `verify`, spies, inline mock maker, `mockStatic`), [`ArgumentCaptor`](https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/ArgumentCaptor.html), [`InjectMocks`](https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/InjectMocks.html), [`MockitoExtension`](https://javadoc.io/doc/org.mockito/mockito-junit-jupiter/latest/org/mockito/junit/jupiter/MockitoExtension.html)
- Mockito wiki: [How to write good tests](https://github.com/mockito/mockito/wiki/How-to-write-good-tests)
