Mockito: mocks, spies and verification

Mockito replaces a class's collaborators with mocks, so a unit test can script their answers and check how they were called. This page explains test doubles and how Mockito builds them, then runs real tests for stubbing, verification, captors and strict stubs, final classes, spies and static mocks, two common traps, and the Java agent setup that current JDKs need.

Share

Contents

Test doubles and how Mockito makes them

A unit test should exercise one class, but real classes call others: a payment gateway, a database, a clock. A test double stands in for such a collaborator. The common kinds are:

  • Stub: returns canned answers, such as "order 7 costs 19.99".
  • Mock: a stub that also records calls, so the test can verify what was called, with which arguments and in which order.
  • Spy: wraps a real object, calls its real methods, and lets selected methods be stubbed.
  • Fake: a working but simplified implementation, such as an in-memory repository. Mockito does not make fakes; you write them.

Mockito creates mocks and spies at run time. Since Mockito 5 the default inline mock maker uses Byte Buddy and the JVM's instrumentation API to rewrite the bytecode of the mocked class itself, which is why final classes and static methods can be mocked. Every call to a mock goes to a handler that looks for a matching stubbing, records the invocation, and otherwise returns a default value. when(mock.call()) works because the call inside it is recorded as "the last invocation" and thenReturn attaches an answer to it.

Mockito versions
VersionYearKey change
Mockito 22016Byte Buddy instead of CGLIB; strict stubbing introduced; Java 6+
Mockito 3 and 42019, 2021Java 8 baseline; mockStatic (3.4); deprecated APIs removed in 4
Mockito 52023Java 11 baseline; inline mock maker is the default, so final classes are mockable without configuration

The tests on this page were run with Mockito 5.17 and JUnit 5.12 on JDK 21.

The class under test

OrderService.pay looks up an order's total, charges it through a payment gateway, and records the transaction id. Free orders skip the gateway. Its two collaborators are interfaces passed into the constructor, which is what makes the class easy to test.

Java
import java.math.BigDecimal;
import java.util.Optional;

// Code under test with two collaborators we do not want to call for real in a unit test
public class OrderService {

    public interface PaymentGateway {
        String charge(String customerId, BigDecimal amount);   // returns a transaction id
    }

    public interface OrderRepository {
        Optional<BigDecimal> findTotal(long orderId);

        void markPaid(long orderId, String transactionId);
    }

    private final PaymentGateway gateway;
    private final OrderRepository repo;

    public OrderService(PaymentGateway gateway, OrderRepository repo) {
        this.gateway = gateway;
        this.repo = repo;
    }

    public String pay(long orderId, String customerId) {
        BigDecimal total = repo.findTotal(orderId)
                .orElseThrow(() -> new IllegalArgumentException("no order " + orderId));
        if (total.signum() == 0) {
            repo.markPaid(orderId, "FREE");
            return "FREE";
        }
        String tx = gateway.charge(customerId, total);
        repo.markPaid(orderId, tx);
        return tx;
    }
}

The tests

Each test arranges the mocks' answers with when(...).thenReturn(...), calls the service, and then checks the result and the calls made to the mocks. The last test contains a mistake on purpose.

Java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

import java.math.BigDecimal;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {

    @Mock
    OrderService.PaymentGateway gateway;

    @Mock
    OrderService.OrderRepository repo;

    @InjectMocks
    OrderService service;                            // created with the two mocks

    @Test
    @DisplayName("charges the order total and stores the transaction id")
    void paysOrder() {
        when(repo.findTotal(7L)).thenReturn(Optional.of(new BigDecimal("19.99")));
        when(gateway.charge("cust-1", new BigDecimal("19.99"))).thenReturn("tx-42");

        assertEquals("tx-42", service.pay(7L, "cust-1"));

        InOrder order = inOrder(gateway, repo);
        order.verify(gateway).charge("cust-1", new BigDecimal("19.99"));
        order.verify(repo).markPaid(7L, "tx-42");
    }

    @Test
    @DisplayName("free orders never reach the payment gateway")
    void freeOrder() {
        when(repo.findTotal(8L)).thenReturn(Optional.of(BigDecimal.ZERO));

        assertEquals("FREE", service.pay(8L, "cust-1"));

        verifyNoInteractions(gateway);
        ArgumentCaptor<String> tx = ArgumentCaptor.forClass(String.class);
        verify(repo).markPaid(eq(8L), tx.capture());
        assertEquals("FREE", tx.getValue());
    }

    @Test
    @DisplayName("an unknown order fails before any payment")
    void unknownOrder() {
        when(repo.findTotal(9L)).thenReturn(Optional.empty());

        assertThrows(IllegalArgumentException.class, () -> service.pay(9L, "cust-1"));
        verify(gateway, never()).charge(anyString(), any());
    }

    @Test
    @DisplayName("a gateway failure leaves the order unpaid")
    void gatewayFails() {
        when(repo.findTotal(7L)).thenReturn(Optional.of(BigDecimal.TEN));
        when(gateway.charge(anyString(), any())).thenThrow(new IllegalStateException("declined"));

        assertThrows(IllegalStateException.class, () -> service.pay(7L, "cust-1"));
        verify(repo, never()).markPaid(any(Long.class), anyString());
    }

    @Test
    @DisplayName("strict stubs: an unused stubbing fails the test")
    void unusedStub() {
        when(repo.findTotal(7L)).thenReturn(Optional.of(BigDecimal.ONE));
        when(gateway.charge("someone-else", BigDecimal.ONE)).thenReturn("tx-1");   // never used
        when(gateway.charge("cust-1", BigDecimal.ONE)).thenReturn("tx-2");
        assertEquals("tx-2", service.pay(7L, "cust-1"));
    }
}

Run with the same JUnit launcher as on the JUnit 5 page:

Output
PASS  an unknown order fails before any payment
PASS  a gateway failure leaves the order unpaid
PASS  free orders never reach the payment gateway
PASS  charges the order total and stores the transaction id
FAIL  strict stubs: an unused stubbing fails the test
      UnnecessaryStubbingException: 
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at OrderServiceTest.unusedStub(OrderServiceTest.java:84)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.
tests: 5, passed: 4, failed: 1, aborted: 0, skipped: 0

What each test demonstrates:

  1. Stubbing and order: the mocks return the scripted total and transaction id, and InOrder confirms the charge happened before the order was marked paid. Marking an order paid before the money is taken would be a real bug.
  2. No interaction: for a free order, verifyNoInteractions(gateway) proves the payment provider was never contacted. An ArgumentCaptor captures the value passed to markPaid so it can be checked with a normal assertion.
  3. Failure path: with no order found, the service throws and verify(gateway, never()) confirms nothing was charged. Matchers such as anyString() and any() match any argument.
  4. Exceptions from a mock: thenThrow simulates a declined payment; the test checks the order was not marked paid.
  5. Strict stubs: MockitoExtension fails a test that sets up a stubbing it never uses, with UnnecessaryStubbingException pointing at the line. Unused stubbings usually mean the test does not test what its author thinks, here a stub for the wrong customer. Use lenient() only for stubs that are intentionally optional.

A mock returns default values for unstubbed calls: null for objects, 0 and false for primitives, and empty collections and Optionals. That is why each test stubs findTotal explicitly.

Answers, void methods, BDD style and verification traps

thenReturn covers most stubbing, but real collaborators fail on the first try, compute results from their input or return nothing at all. The third test class shows the other ways to script a mock, and two traps: a stub that silently does not match, and verification that is too strict. One test fails on purpose.

Java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.math.BigDecimal;
import org.junit.jupiter.api.Test;

class AnswersTest {

    interface Gateway {
        String charge(String customer, BigDecimal amount);

        void refund(String tx);
    }

    @Test
    void consecutiveAnswers() {
        Gateway g = mock(Gateway.class);
        when(g.charge(anyString(), any()))
                .thenThrow(new IllegalStateException("timeout"))   // first call
                .thenReturn("tx-1", "tx-2");                       // then these, then tx-2
        assertThrows(IllegalStateException.class, () -> g.charge("a", BigDecimal.ONE));
        assertEquals("tx-1", g.charge("a", BigDecimal.ONE));
        assertEquals("tx-2", g.charge("a", BigDecimal.ONE));
        assertEquals("tx-2", g.charge("a", BigDecimal.ONE));
        verify(g, times(4)).charge(anyString(), any());
    }

    @Test
    void answerComputedFromArguments() {
        Gateway g = mock(Gateway.class);
        when(g.charge(anyString(), any())).thenAnswer(inv ->
                "tx-" + inv.getArgument(0) + "-" + inv.<BigDecimal>getArgument(1).intValue());
        assertEquals("tx-ana-20", g.charge("ana", new BigDecimal("20.50")));
    }

    @Test
    void voidMethodThrows() {
        Gateway g = mock(Gateway.class);
        doThrow(new IllegalArgumentException("unknown tx")).when(g).refund("tx-9");
        assertThrows(IllegalArgumentException.class, () -> g.refund("tx-9"));
        g.refund("tx-1");                                          // other values: no-op
        verify(g, atLeastOnce()).refund(argThat(tx -> tx.startsWith("tx-")));
    }

    @Test
    void bddStyle() {
        Gateway g = mock(Gateway.class);
        given(g.charge("ana", BigDecimal.TEN)).willReturn("tx-7");
        assertEquals("tx-7", g.charge("ana", BigDecimal.TEN));
        then(g).should().charge("ana", BigDecimal.TEN);
        verifyNoMoreInteractions(g);
    }

    @Test
    void stubbedWithEqualButDifferentBigDecimal() {
        Gateway g = mock(Gateway.class);
        when(g.charge("ana", new BigDecimal("19.99"))).thenReturn("tx-1");
        // 19.990 is numerically equal, but BigDecimal.equals says no, so no stub matches
        assertNull(g.charge("ana", new BigDecimal("19.990")));
    }

    @Test
    void verifyTooStrict() {
        Gateway g = mock(Gateway.class);
        g.charge("ana", BigDecimal.ONE);
        g.refund("tx-1");                                         // a call the test forgot
        verify(g).charge("ana", BigDecimal.ONE);
        verifyNoMoreInteractions(g);
    }
}

Output:

Output
PASS  stubbedWithEqualButDifferentBigDecimal()
FAIL  verifyTooStrict()
      NoInteractionsWanted: 
No interactions wanted here:
-> at AnswersTest.verifyTooStrict(AnswersTest.java:81)
But found this interaction on mock 'gateway':
-> at AnswersTest.verifyTooStrict(AnswersTest.java:79)
***
For your reference, here is the list of all invocations ([?] - means unverified).
1. -> at AnswersTest.verifyTooStrict(AnswersTest.java:78)
2. [?]-> at AnswersTest.verifyTooStrict(AnswersTest.java:79)

PASS  voidMethodThrows()
PASS  bddStyle()
PASS  consecutiveAnswers()
PASS  answerComputedFromArguments()
tests: 6, passed: 5, failed: 1, aborted: 0, skipped: 0
  • consecutiveAnswers: chained answers are used in order, and the last one repeats. The first call threw "timeout", then came tx-1, then tx-2 twice. This is how a retry loop is tested. times(4) confirmed all four calls.
  • answerComputedFromArguments: thenAnswer receives the invocation, so the result can depend on the arguments: "ana" and 20.50 gave "tx-ana-20".
  • voidMethodThrows: a void method cannot appear inside when(...), so doThrow(...).when(mock).refund(...) is used instead. argThat verified the call with a condition rather than an exact value.
  • bddStyle: given, willReturn and then(...).should() are aliases from BDDMockito that read in the given/when/then structure of behaviour-driven tests. They behave exactly like when and verify.
  • stubbedWithEqualButDifferentBigDecimal passed, but it documents a trap: the stub for 19.99 did not match a call with 19.990, because argument matching uses equals, and BigDecimal.equals compares the scale. The mock returned null with no warning. Use argThat(a -> a.compareTo(x) == 0) or normalize amounts in the code under test.
  • verifyTooStrict failed with NoInteractionsWanted because of an extra refund call. The message lists all invocations and marks the unverified one with [?]. Calling verifyNoMoreInteractions in every test makes tests fail whenever the implementation adds a harmless call; keep it for the few cases where "nothing else happened" is the point.

Final classes, spies, static methods and two traps

The second test class shows features that need the inline mock maker, plus the two mistakes that most often confuse newcomers. Two tests fail on purpose.

Java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;

class AdvancedMockitoTest {

    // A final class: mockable because Mockito 5 uses the inline mock maker by default
    static final class TaxTable {
        int rate(String country) {
            return 25;
        }
    }

    static final class Calendar {
        static LocalDate today() {
            return LocalDate.now();
        }
    }

    @Test
    void finalClass() {
        TaxTable table = mock(TaxTable.class);
        when(table.rate("NO")).thenReturn(15);
        assertEquals(15, table.rate("NO"));
        assertEquals(0, table.rate("SE"));               // unstubbed: default value
    }

    @Test
    void spyCallsRealMethods() {
        List<String> list = spy(new ArrayList<String>());
        list.add("a");
        doReturn(100).when(list).size();                 // stub one method, keep the rest
        assertEquals(100, list.size());
        assertEquals("a", list.get(0));                  // real method
        verify(list, times(1)).add("a");
    }

    @Test
    void whenOnSpyCallsTheRealMethod() {
        List<String> list = spy(new ArrayList<String>());
        when(list.get(0)).thenReturn("x");               // calls the real get(0) first: throws
    }

    @Test
    void staticMethod() {
        try (MockedStatic<Calendar> cal = mockStatic(Calendar.class)) {
            cal.when(Calendar::today).thenReturn(LocalDate.of(2026, 1, 15));
            assertEquals(LocalDate.of(2026, 1, 15), Calendar.today());
        }
        // outside the try block the real method is back
        assertEquals(LocalDate.now(), Calendar.today());
    }

    @Test
    void mixingMatchersAndValues() {
        Map<String, Integer> stock = mock();
        when(stock.getOrDefault(anyString(), 0)).thenReturn(1);   // matcher plus raw value
    }
}

Output:

Output
PASS  finalClass()
PASS  spyCallsRealMethods()
FAIL  whenOnSpyCallsTheRealMethod()
      IndexOutOfBoundsException: Index 0 out of bounds for length 0
PASS  staticMethod()
FAIL  mixingMatchersAndValues()
      InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at AdvancedMockitoTest.mixingMatchersAndValues(AdvancedMockitoTest.java:70)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(any(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(any(), eq("String by matcher"));

For more info see javadoc for Matchers class.

tests: 5, passed: 3, failed: 2, aborted: 0, skipped: 0
  • finalClass passed: the final TaxTable was mocked with no extra setup. The unstubbed call for "SE" returned 0, the default for int.
  • spyCallsRealMethods passed: size() returned the stubbed 100, while get(0) ran the real method and returned "a".
  • whenOnSpyCallsTheRealMethod failed with IndexOutOfBoundsException. In when(list.get(0)) the real get(0) runs before Mockito can intercept it, and the list is empty. For spies, use doReturn("x").when(list).get(0), which never calls the real method.
  • staticMethod passed: inside the try-with-resources block Calendar.today() returned the fixed date, and after closing the MockedStatic the real method was back. Static mocks apply only to the current thread, and forgetting to close one leaks it into later tests.
  • mixingMatchersAndValues failed with InvalidUseOfMatchersException, "2 matchers expected, 1 recorded". When any argument uses a matcher, all must: write eq(0) instead of 0.

Mocking static methods and final classes is useful for legacy code, but needing it often is a sign that a dependency should be passed in, as OrderService does, or replaced by an injectable Clock.

Mocks or fakes?

Mocks are not the only test double. For collaborators with simple behaviour, a hand-written fake is often clearer. The test below checks the same payment as paysOrder, with an in-memory repository and a lambda as the gateway, and no Mockito at all.

Java
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;

// The same behaviour tested with hand-written fakes instead of mocks: check state, not calls
class FakeRepositoryTest {

    static final class InMemoryOrders implements OrderService.OrderRepository {
        final Map<Long, BigDecimal> totals = new HashMap<>();
        final Map<Long, String> paid = new HashMap<>();

        @Override
        public Optional<BigDecimal> findTotal(long orderId) {
            return Optional.ofNullable(totals.get(orderId));
        }

        @Override
        public void markPaid(long orderId, String transactionId) {
            paid.put(orderId, transactionId);
        }
    }

    @Test
    void paysOrder() {
        InMemoryOrders orders = new InMemoryOrders();
        orders.totals.put(7L, new BigDecimal("19.99"));
        OrderService service = new OrderService((customer, amount) -> "tx-" + customer, orders);

        service.pay(7L, "cust-1");

        assertEquals(Map.of(7L, "tx-cust-1"), orders.paid);      // the resulting state
    }
}

Output:

Output
PASS  paysOrder()
tests: 1, passed: 1, failed: 0, aborted: 0, skipped: 0

The fake test checks the result: order 7 ended up paid with transaction "tx-cust-1". The mock test checked the calls: charge then markPaid with certain arguments. A state-based test survives refactorings that change how the service talks to the repository, such as batching updates, while an interaction-based test breaks. The cost is writing and maintaining the fake. A common balance is fakes for repositories and in-memory stores, and mocks for collaborators whose calls are the behaviour, such as sending an email or charging a card.

Running Mockito on JDK 21 and later

Mockito 5 creates mocks with an inline mock maker that needs a Java agent. Without configuration, it attaches the agent itself at run time, and current JDKs warn about that (JEP 451). Running the tests above without any extra flag printed:

Output
Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build as described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org.mockito/org/mockito/Mockito.html#0.3
WARNING: A Java agent has been loaded dynamically (.../byte-buddy-agent-1.17.7.jar)
WARNING: Dynamic loading of agents will be disallowed by default in a future release

The output above was produced with -javaagent:mockito-core-5.17.0.jar instead, which loads the agent at start-up and removes the warnings. In Maven, configure Surefire's argLine with -javaagent:${org.mockito:mockito-core:jar} (using the dependency plugin's properties goal); in Gradle, add the JAR to the test task's jvmArgs.

Choosing what to mock

When to mock
MockDo not mock
Collaborators with side effects: payment, email, external APIsValue types such as records, BigDecimal, collections
Slow or non-deterministic dependenciesThe class under test itself
Interfaces you ownThird-party types you do not own; wrap them in your own interface first
Time, through an injected ClockStatic methods, if passing a dependency is possible
A real object with one awkward method: a spy with doReturnSimple in-memory logic; a fake is clearer

For HTTP clients, a fake server is often better than a mock, because it also tests the serialization and the HTTP handling; see WireMock. Verify only the interactions that matter to the behavior; tests that verify every call break whenever the implementation changes.