Skip to content
javahacks.dev
Testing

Mockito Tutorial for Mocks Stubs and Verification in Java

A Mockito tutorial: create mocks, stub return values and exceptions, verify calls and arguments, and know where mocks help a test and where they hurt.

6 min read
Summarize in AI
Flat illustration of a real object swapped for a mock on strings, with the JUnit5, Spring Boot and GitHub Actions logos.

Mockito replaces a collaborator with a stand-in you control, so a test can exercise one class without a database, a payment provider or a clock. This tutorial uses Mockito 5 with JUnit 5 on JDK 25 and walks from the first mock to the judgement calls that decide whether a mock-heavy test suite helps or hurts. The vocabulary of mocks, stubs, spies and fakes is laid out in test doubles, and it is worth reading once, because a lot of Mockito misuse is a vocabulary problem.

Set up

Spring Boot's test starter already pulls Mockito in. In a plain project add the JUnit 5 integration, which brings mockito-core with it:

XML
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-junit-jupiter</artifactId>
  <scope>test</scope>
</dependency>

Mockito 5 uses the inline mock maker by default, so final classes and final methods can be mocked without extra configuration. That removes the most common complaint from older versions, and the details are in mocking final classes.

The class under test

A checkout service has two collaborators: a payment gateway it cannot call for real in a test, and a repository it should not need a database for.

java
class CheckoutService {

    private final PaymentGateway gateway;
    private final OrderRepository orders;

    CheckoutService(PaymentGateway gateway, OrderRepository orders) {
        this.gateway = gateway;
        this.orders = orders;
    }

    Receipt checkout(Order order) {
        PaymentResult result = gateway.charge(order.customerId(), order.total());
        if (!result.approved()) {
            throw new PaymentDeclinedException(result.reason());
        }
        orders.markPaid(order.id());
        return new Receipt(order.id(), result.reference());
    }
}

Constructor injection is what makes this testable. A class that builds its own gateway inside the method leaves a test nowhere to put a mock.

A first test

java
@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {

    @Mock PaymentGateway gateway;
    @Mock OrderRepository orders;
    @InjectMocks CheckoutService service;

    @Test
    void marksTheOrderPaidWhenTheChargeIsApproved() {
        Order order = new Order(7L, "cust-1", Money.of(25));
        when(gateway.charge("cust-1", Money.of(25))).thenReturn(PaymentResult.approved("ref-9"));

        Receipt receipt = service.checkout(order);

        assertEquals("ref-9", receipt.reference());
        verify(orders).markPaid(7L);
    }

    @Test
    void doesNotTouchTheRepositoryWhenDeclined() {
        when(gateway.charge(any(), any())).thenReturn(PaymentResult.declined("insufficient funds"));

        assertThrows(PaymentDeclinedException.class,
                () -> service.checkout(new Order(7L, "cust-1", Money.of(25))));

        verifyNoInteractions(orders);
    }
}

@ExtendWith(MockitoExtension.class) creates the annotated mocks before each test and checks for unused stubs afterwards. @InjectMocks builds the service through its constructor with those mocks. Read the first test in three parts. The when line is arrange: it tells the fake gateway what to answer. The checkout call is act. The assertion on the receipt and the verify are assert: one on the result the caller sees, one on the side effect that matters. The extension details are in using Mockito with JUnit 5.

Stubbing

GoalCode
Return a valuewhen(m.find(1)).thenReturn(x)
Different values in turnthenReturn(a, b, c)
Throwwhen(m.find(1)).thenThrow(new IOException())
Compute from argumentsthenAnswer(inv -> inv.getArgument(0))
Void method throwsdoThrow(...).when(m).run()

An unstubbed method returns the default for its type: null for objects, 0, false, and an empty List, Map or Optional. That surprises people who expect an exception, and it is why a test that forgets a stub often fails later with a NullPointerException far from the cause. Arguments in when must equal what the code passes, or you use matchers such as any() and eq(). The rule that matters: once one argument uses a matcher, all of them must. ArgumentCaptor and matchers covers the traps, and stubbing void methods covers the doThrow form.

Verification

java
verify(orders).markPaid(7L);                     // exactly once
verify(orders, times(2)).save(any());
verify(orders, never()).delete(any());
verifyNoMoreInteractions(orders);

Use verify for commands whose effect is the point: an email sent, a payment captured, an event published. For queries, stub the answer and assert on the returned value instead, because a verified query call proves nothing about behaviour. Over-verifying is the habit that makes mock-based suites hated. A test that pins every call, in order, on every collaborator fails when you refactor without changing behaviour, and the team learns to fix tests by editing them to match the code.

Capturing what was passed

When the interesting part is the argument, capture it.

java
ArgumentCaptor<Invoice> captor = ArgumentCaptor.forClass(Invoice.class);
verify(invoices).save(captor.capture());
assertEquals(Money.of(25), captor.getValue().total());

This lets you assert on an object the code built internally, without exposing it through the return value.

When a mock is the wrong tool

Value objects and simple data should be built for real. An Order is a record, so create one; mocking it hides the constructor and the equality you may depend on. A collaborator with trivial logic is clearer as a hand-written fake or an in-memory implementation than as twelve stubs. And the thing you actually want to test must stay real: a test that mocks the database to check a SQL query tests nothing, and a repository belongs in a test with a real database, as in Testcontainers for databases.

A suite made only of mocks proves that the code matches the author's picture of how its collaborators behave, not that the system works. The balance between unit, slice and integration tests is argued in the testing strategy.

Mocks, spies and the question of intent

A mock has no behaviour of its own, and a spy wraps a real object and lets you override a few methods. Reach for a spy rarely. A test that needs a spy is often telling you the class does too much, and partial mocking hides that. When you do need one, the safe form is doReturn(x).when(spy).method(), because when(spy.method()) calls the real method first. The costs and the alternatives are in spies without hurting the design.

Name tests for the behaviour, not the method: doesNotTouchTheRepositoryWhenDeclined reads as a requirement, and testCheckout2 reads as nothing. When a test needs more than three stubs to set up, treat that as feedback. Either the class has too many collaborators, or the test is covering too many branches at once, and splitting it is cheaper than maintaining it.

Failures worth recognising

UnnecessaryStubbingException means a stub was set up and never used, which strict stubs treat as a bug; see strict stubs. NotAMockException means verify was called on a real object. WrongTypeOfReturnValue means a thenReturn value does not match the method's type, usually after a stubbing chain was typed against the wrong mock.

Organising mocks in a larger test class

When a test class needs five or six mocks, the class under test probably has too many collaborators. Group related behaviour behind a smaller interface, or build a small fake that holds state instead of stubbing each call. Keep mocks as fields annotated with @Mock, create the object under test in a @BeforeEach method when construction needs more than @InjectMocks can do, and reset nothing by hand: the extension creates fresh mocks for each test.

Name stubs after the scenario, not after the method, so a reader can see why a value is returned.

Where Mockito is not enough

Static methods and constructors can be mocked with the inline maker, but doing so is usually a sign that a seam is missing, as in mocking static methods. Time and randomness are better injected as a Clock and a seeded Random than mocked. References: the Mockito Javadoc and the project site.

Also inJUnit
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.