Mockito: mocks, stubs and spies

Junior Always asked 7 min

On this page

The question

What is the difference between a mock, a stub, a spy and a fake?

30-second answer

All four are test doubles that stand in for a real dependency. A stub returns canned answers, and the test checks the result. A mock records calls, and the test verifies the interaction. A spy wraps a real object, so real methods run unless stubbed. A fake is a working, simpler implementation, such as an in-memory repository. In Mockito, one mock() object can be both stubbed and verified.

Understand it

Mock, stub, spy and fake

Compare

A stub answers with canned values so the code under test can run. The test then checks the result, not the calls.

View as text

OrderService calls a PaymentGateway, which is replaced by a test double. Four rows describe the double: what it answers with, whether real code runs, whether calls are checked, and what the test checks. A line of code at the bottom creates or uses it.

A stub answers with canned values so the code under test can run. The test then checks the result, not the calls. It answers with canned values; real code: no; calls: not checked. Code: when(gw.charge(20)).thenReturn(true);

A mock records every call so the test can verify the interaction. In Mockito, the same mock() object can also be stubbed. It answers with defaults unless stubbed; real code: no; calls: recorded, then verified. Code: verify(gw).charge(20);

A spy wraps a real object: real methods run unless you stub one, and calls are recorded. Use it sparingly, often on legacy code. It answers with real methods; real code: yes, unless stubbed; calls: recorded, then verified. Code: spy(new RealGateway());

A fake is a working, lighter implementation, such as an in-memory repository. It needs no Mockito, and the test checks the state it ends in. It answers with working, simple logic; real code: its own, simplified; calls: not checked. Code: new InMemoryOrders();

OrderService calls a PaymentGateway, which is replaced by a test double. Four rows describe the double: what it answers with, whether real code runs, whether calls are checked, and what the test checks. A line of code at the bottom creates or uses it.

A stub answers with canned values so the code under test can run. The test then checks the result, not the calls. It answers with canned values; real code: no; calls: not checked. Code: when(gw.charge(20)).thenReturn(true);

A mock records every call so the test can verify the interaction. In Mockito, the same mock() object can also be stubbed. It answers with defaults unless stubbed; real code: no; calls: recorded, then verified. Code: verify(gw).charge(20);

A spy wraps a real object: real methods run unless you stub one, and calls are recorded. Use it sparingly, often on legacy code. It answers with real methods; real code: yes, unless stubbed; calls: recorded, then verified. Code: spy(new RealGateway());

A fake is a working, lighter implementation, such as an in-memory repository. It needs no Mockito, and the test checks the state it ends in. It answers with working, simple logic; real code: its own, simplified; calls: not checked. Code: new InMemoryOrders();

Takeaway: Stubs and fakes feed the code so you can check results; mocks and spies record calls so you can verify interactions. A spy also runs real code.

A mock intercepting calls

Step by step

@Mock, or mock(PaymentGateway.class), creates an object of a generated class that implements the interface. None of the real gateway code is in it.

Step 1 of 6
View as text

A test and OrderService on the left. On the right, the mock gateway lists its stubbed rules and the calls it has recorded. Below it, the real gateway stays faded. The current line of test code is at the bottom.

@Mock, or mock(PaymentGateway.class), creates an object of a generated class that implements the interface. None of the real gateway code is in it. The real gateway is marked never called.

when(gw.charge(20)).thenReturn(true) stores a rule in the mock: these arguments get this answer. The rule charge(20) returns true appears.

@InjectMocks builds OrderService and passes the mock to its constructor. The service cannot tell it from the real gateway. An arrow joins the service to the mock.

checkout(20) calls gw.charge(20). The mock records the call, finds the matching rule and returns true, so the order is PAID. The call log shows charge(20).

checkout(99) calls charge(99). No rule matches, so the mock returns the default, false, and the order is DECLINED, with no error. The log adds charge(99), and a mark reads no rule: default false.

verify(gw).charge(20) checks the recorded calls. It passes; had the call never happened, Mockito would fail with WantedButNotInvoked. A mark reads verify passes.

A test and OrderService on the left. On the right, the mock gateway lists its stubbed rules and the calls it has recorded. Below it, the real gateway stays faded. The current line of test code is at the bottom.

@Mock, or mock(PaymentGateway.class), creates an object of a generated class that implements the interface. None of the real gateway code is in it. The real gateway is marked never called.

when(gw.charge(20)).thenReturn(true) stores a rule in the mock: these arguments get this answer. The rule charge(20) returns true appears.

@InjectMocks builds OrderService and passes the mock to its constructor. The service cannot tell it from the real gateway. An arrow joins the service to the mock.

checkout(20) calls gw.charge(20). The mock records the call, finds the matching rule and returns true, so the order is PAID. The call log shows charge(20).

checkout(99) calls charge(99). No rule matches, so the mock returns the default, false, and the order is DECLINED, with no error. The log adds charge(99), and a mark reads no rule: default false.

verify(gw).charge(20) checks the recorded calls. It passes; had the call never happened, Mockito would fail with WantedButNotInvoked. A mark reads verify passes.

Takeaway: A mock answers from rules you stub, falls back to defaults such as false, null or an empty list, and records every call so verify can check it.

Which test double the test needsIf the test needs a canned answer, use a stub. To check that a call was made, use a mock. To run a real object but change or watch one method, use a spy. To have a working in-memory version, use a fake.What does thetest need?A canned answer:stubCheck a call:mockReal object, onemethod changed:spyWorking, in memory:fake
Which test double the test needsIf the test needs a canned answer, use a stub. To check that a call was made, use a mock. To run a real object but change or watch one method, use a spy. To have a working in-memory version, use a fake.What does thetest need?A canned answer:stubCheck a call:mockReal object, onemethod changed:spyWorking, in memory:fake
Which test double the test needs

In code

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
    @Mock PaymentGateway gateway;
    @InjectMocks OrderService service;           // the mock goes into its constructor

    @Test
    void paysWhenTheGatewayAccepts() {
        when(gateway.charge(20)).thenReturn(true);   // stub

        String status = service.checkout(20);        // act

        assertEquals("PAID", status);                // check the result
        verify(gateway).charge(20);                  // check the interaction
    }
}
Stub the answer, act, then check result and call
@Test
void sendsTheReceiptToTheCustomer() {
    when(gateway.charge(20)).thenReturn(true);
    service.checkout(new Order("[email protected]", 20));

    ArgumentCaptor<Email> email = ArgumentCaptor.forClass(Email.class);
    verify(mailer).send(email.capture());
    assertEquals("[email protected]", email.getValue().to());
}

@Test
void spyRunsRealCodeUnlessStubbed() {
    PaymentGateway spy = spy(new RealGateway());
    doReturn(false).when(spy).charge(5);         // when(spy.charge(5)) would run the real method first
    assertFalse(spy.charge(5));
}
Capture an argument, and stub a spy safely
checkout of 20 against a mocked gatewayThe test calls checkout with 20. The service calls charge with 20 on the mock, which records the call, matches the stubbed rule and returns true. The service returns PAID, and verify finds the recorded call.Test: checkout(20)Service callsgw.charge(20)Mock records thecallRule matches: trueService returns PAIDverify finds the call
checkout of 20 against a mocked gatewayThe test calls checkout with 20. The service calls charge with 20 on the mock, which records the call, matches the stubbed rule and returns true. The service returns PAID, and verify finds the recorded call.Test: checkout(20)Service callsgw.charge(20)Mock records thecallRule matches: trueService returns PAIDverify finds the call
checkout(20) against a mocked gateway
when(gateway.charge(any())).thenThrow(new PaymentDeclinedException("card declined"));

assertThrows(PaymentDeclinedException.class, () -> checkout.pay(order));
verify(orders, never()).markPaid(any());       // the order stays unpaid
verify(mailer, never()).sendReceipt(any());    // and no receipt goes out
Stub a failure, then verify what must not happen

Solve it

The mock returns 0 and the test passes for the wrong reason

OrderServiceTest stubs when(prices.priceOf("A1")).thenReturn(10) and asserts that the total for two A1 items is not negative. It passes, yet production totals are 0: the service lowercases SKUs before the lookup. Explain and fix it.

  1. Know the defaults. An unstubbed call on a mock returns 0, false, null or an empty collection. The service asked for "a1" and got 0.
  2. Read the assertion again. “Not negative” holds for 0 as well as for 20, so the bug could never fail it. Assert the exact expected value.
  3. Let Mockito complain. With MockitoExtension, strict stubs throw PotentialStubbingProblem when a stubbed method is called with other arguments, and UnnecessaryStubbingException for a stub never used.
  4. Fix the right side. Decide whether SKUs are case-insensitive. Fix the service or the stub, then assert the total and verify the exact argument.
  5. Check. Break the code on purpose, for example by returning 0: the test must fail.
@ExtendWith(MockitoExtension.class)            // strict stubs by default
class OrderServiceTest {
    @Mock PriceClient prices;
    @InjectMocks OrderService service;

    @Test
    void totalsTwoItems() {
        when(prices.priceOf("A1")).thenReturn(10);

        int total = service.total(List.of("A1", "A1"));   // a call with "a1" now fails the test

        assertEquals(20, total);
        verify(prices, times(2)).priceOf("A1");
    }
}
Strict stubs plus an exact result catch the mismatch

How to answer

  • Stubs and fakes support state checks; mocks and spies support interaction checks.
  • Unstubbed calls on a Mockito mock return defaults, such as false, 0, null or an empty list.
  • A fake needs no framework and often makes tests easier to read.
  • Verify only interactions that matter, such as a payment being charged.

Common mistakes

  • Using "mock" for every kind of double, so the difference between state and interaction checks is lost.
  • Verifying every call, which ties the test to the implementation.

Follow-up questions

What is the difference between when(...).thenReturn(...) and verify(...)?

when(...).thenReturn(...) happens before the act: it tells the mock what to answer, so the code under test can run. verify(...) happens after: it checks that a call happened, with the given arguments and how many times. Stub what the code needs to read, and verify what the code must do, such as charging a card or sending an email.

  • Do not verify a call you also stubbed just to feed the code; the result already proves it.
  • verify(mock, never()) checks that something did not happen.
  • times(n), atLeastOnce() and argument matchers like eq() refine a check.

See it in the infographic: A mock intercepting calls

What does @InjectMocks do?

It creates the object under test and passes it the @Mock and @Spy fields of the test class. Mockito tries constructor injection with the biggest constructor first, then setters, then fields. A dependency with no matching mock gets null, with no error, so a test can fail far from the cause. Constructor injection in the class keeps it predictable, and plain new OrderService(gateway) works just as well.

  • It needs MockitoExtension or MockitoAnnotations.openMocks(this) to run.
  • Mocks are matched to parameters by type, then by name.
  • It is a Mockito feature, unrelated to Spring's context.

See it in the infographic: A mock intercepting calls

When do you use an ArgumentCaptor?

When the code under test builds an object inside and passes it to a dependency, and the test needs to check that object's fields. Verify the call with captor.capture() as the argument, then assert on getValue(). For a simple value, an exact argument or a matcher in verify is clearer than a captor.

  • Capture inside verify, not inside when.
  • getAllValues() returns every captured value when the call happened several times.
  • argThat(...) is an alternative for a one-line condition.
ArgumentCaptor<Email> email = ArgumentCaptor.forClass(Email.class);
verify(mailer).send(email.capture());
assertEquals("[email protected]", email.getValue().to());

See it in the infographic: A mock intercepting calls

What goes wrong when a test mocks every collaborator?

The test starts describing the implementation instead of the behavior. Every refactoring that changes which methods get called breaks it, even when the result is the same, and it can pass while the real parts do not fit together. Mock what is slow or outside your control, such as payment, email or the clock. Use real objects or fakes for simple collaborators.

  • Do not mock value objects or simple data classes.
  • Prefer not to mock types you do not own; wrap them and test the wrapper with an integration test.
  • A test with many mocks often points to a class with too many dependencies.

See it in the infographic: Mock, stub, spy and fake

Can Mockito mock final classes and static methods?

Yes, with the inline mock maker, which is the default since Mockito 5; Mockito 4 needed the mockito-inline artifact. Static methods are mocked with mockStatic(...) in a try-with-resources block, so the change lasts only inside it. Needing this often is a design smell: inject a Clock or a wrapper instead of mocking a static call.

  • try (var mocked = mockStatic(UUID.class)) { ... } scopes the static mock.
  • The inline mock maker changes the bytecode of the existing class.
  • Private methods still cannot be mocked, by design.

See it in the infographic: Mock, stub, spy and fake

Why does a Mockito mock return false or null for calls you did not stub?

Its default answer, RETURNS_DEFAULTS, returns a neutral value for the type: false, 0, an empty collection, an empty Optional, and null for other objects. That keeps a mock usable without stubbing everything, but a forgotten stub then shows up as a wrong result instead of an error.

What is strict stubbing?

With MockitoExtension, Mockito fails a test that stubs a call it never uses, with UnnecessaryStubbingException. It also reports a stub called with different arguments. This keeps tests free of stale setup. lenient() turns it off for one stub when that is really needed.

Why use doReturn().when() with a spy?

Because when(spy.charge(5)) calls the real charge method while setting up the stub, which may have side effects or throw. doReturn(false).when(spy).charge(5) sets the answer without calling the real method.

Check yourself

1. A mock's boolean charge(int) method was stubbed only for charge(20). What does charge(99) return?
Show answers
  • false: Correct. No rule matches, so the mock returns the default value for boolean.
  • true: Incorrect. The stub applies only to the argument 20.
  • It throws an exception: Incorrect. Unstubbed calls on a mock return defaults instead of throwing.
2. Which test double runs the real class's methods unless you stub them?
Show answers
  • A spy: Correct. It wraps a real object, so calls go to the real methods by default.
  • A mock: Incorrect. A mock contains none of the real code; it returns defaults.
  • A stub: Incorrect. A stub only returns the canned answers it was given.
3. The test calls verify(gw).charge(20), but the code under test never called charge. What happens?
Show answers
  • The test fails with WantedButNotInvoked.: Correct. verify checks the recorded calls and finds none that match.
  • The test passes, because nothing went wrong.: Incorrect. verify exists to catch exactly this missing call.
  • verify returns false and the test continues.: Incorrect. verify does not return a result; it throws when the check fails.