Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 29 ยท Tooling and collaborators

Mocks and Spies with Mockito

Use Mockito with JUnit 6 and TestNG: @Mock, when/thenReturn, verify, ArgumentCaptor, spies and strict stubs, plus a runnable hand-written mock stand-in.

Most classes do not work alone. An order service calls a payment gateway, a notifier sends an email, a repository talks to a database. In a unit test you want to check the order service's own logic, not whether a real card was charged. A test double takes the place of the collaborator, and Mockito is the library most Java teams use to create doubles without writing a class for each one.

This lesson shows Mockito working together with JUnit and TestNG: creating mocks, stubbing answers, verifying calls, capturing arguments, using spies, and why Mockito's strict mode is your friend. The ideas behind test doubles (stub, fake, spy, mock) are explained in Test Doubles and Mockito; here we focus on the test-framework side.

Real versus stand-in. The Mockito code in the plain code blocks is real Mockito usage, shown read-only because the site's Java runner does not have Mockito on its classpath. The two TryIt blocks run real JUnit 6 against a small mock library written in this lesson with java.lang.reflect.Proxy. It copies the shape of Mockito's API (when, thenReturn, verify) so you can see how it works inside, but it is not Mockito and it supports only what the lesson uses.

What Mockito gives you

Mocks Fake collaborators created in one line.
Stubbing Tell a mock what to answer.
Verifying Check which calls happened.
Spies Wrap a real object, override a little.

Mocks replace slow or unsafe collaborators, not the class you are testing.

1 / 2

Adding Mockito

With Maven, add mockito-core for the library and mockito-junit-jupiter for the JUnit integration, both with test scope. Use the same Mockito version for both:

XML
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>${mockito.version}</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-junit-jupiter</artifactId>
  <version>${mockito.version}</version>
  <scope>test</scope>
</dependency>

For TestNG projects, the second artifact is mockito-testng, which provides a listener that does the same job as the JUnit extension. Recent Mockito versions can mock final classes and methods out of the box, so you rarely need special configuration. The test examples below use a small domain that the whole lesson shares:

Java
interface PaymentGateway {
    boolean charge(String customer, int cents);
}

interface Notifier {
    void send(String to, String message);
}

class OrderService {
    private final PaymentGateway gateway;
    private final Notifier notifier;

    OrderService(PaymentGateway gateway, Notifier notifier) {
        this.gateway = gateway;
        this.notifier = notifier;
    }

    String place(String customer, int cents) {
        if (gateway.charge(customer, cents)) {
            notifier.send(customer, String.format("Paid %d.%02d", cents / 100, cents % 100));
            return "PAID";
        }
        return "DECLINED";
    }
}

OrderService receives its collaborators through the constructor. That is what makes it testable: a test passes mocks instead of real objects.

Mocks with the JUnit extension

@ExtendWith(MockitoExtension.class) tells JUnit to create the fields you mark with @Mock before each test and to check afterwards that you used what you set up. Here is the first test written with real Mockito:

Java
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
    @Mock PaymentGateway gateway;
    @Mock Notifier notifier;
    @InjectMocks OrderService service;

    @Test
    void paidOrderChargesOnceAndNotifies() {
        when(gateway.charge("ann", 1250)).thenReturn(true);

        String result = service.place("ann", 1250);

        assertEquals("PAID", result);
        verify(gateway).charge("ann", 1250);
        verify(notifier).send("ann", "Paid 12.50");
    }
}

Three things happen here. @Mock creates a double whose methods return defaults (false, 0, null, an empty collection) until you say otherwise. @InjectMocks builds OrderService and passes the mocks to its constructor. And when(...).thenReturn(...) stubs one specific call: the answer applies only when the arguments match, here "ann" and 1250.

verify(gateway) means "this method was called exactly once with these arguments". Use verify(mock, times(2)), verify(mock, never()) or verifyNoInteractions(mock) for other counts.

How a mock works inside

A mock is an object that records every call it receives and looks up a canned answer. The trick is when(gateway.charge("ann", 1250)): Java evaluates the inner call first, so the mock sees charge("ann", 1250) and remembers it as the "last call". when then returns a stubbing object, and thenReturn(true) attaches the answer to that remembered call. The first TryIt builds exactly this mechanism, in about 60 lines, with a dynamic proxy, and then runs three real JUnit tests against it.

Java A tiny Mockito-style library and three tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that the test asserts the result first ("PAID") and verifies calls second. A test that only verifies calls breaks every time you restructure the implementation; a test that checks results survives refactoring.

Strict stubs

Imagine a stub that no code ever uses. It usually means the test no longer tests what you think: perhaps the implementation changed, or the test stubs the wrong argument. MockitoExtension runs in strict mode by default and fails the test with UnnecessaryStubbingException when a stub was never used. A stubbed call with different arguments than the code used (an "argument mismatch") is also reported. If a stub is truly needed only in some paths, mark it lenient().when(...), or relax a whole class with @MockitoSettings(strictness = Strictness.LENIENT). Use these sparingly; strictness is the feature.

Capturing arguments

Sometimes you want to inspect an argument, not match it exactly. A message may contain a timestamp, or a collaborator receives an object the service built itself. Mockito's ArgumentCaptor collects the arguments passed to a verified call:

Java
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;

@Captor ArgumentCaptor<String> messageCaptor;

@Test
void notificationMentionsTheAmount() {
    when(gateway.charge("ann", 1250)).thenReturn(true);

    service.place("ann", 1250);

    verify(notifier).send(eq("ann"), messageCaptor.capture());
    assertTrue(messageCaptor.getValue().contains("12.50"));
}

When one argument uses a matcher (eq, any, anyInt, captor.capture()), every argument of that call must use a matcher. Mixing send("ann", any()) is an InvalidUseOfMatchersException. The second TryIt adds capturing and a strict-stub check to the stand-in, so you can watch a "sloppy" test being caught.

Java Capturing arguments and catching unused stubs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first test passes. The second one asserts nothing wrong, yet it fails in @AfterEach because one stub was never used. That is the kind of silent drift strict stubs catch. In real Mockito you get this behavior without writing the check, just by using MockitoExtension.

Spies

A spy wraps a real object: calls go to the real code unless you override them. It is handy for a legacy class you cannot easily split, but it is also a smell, because you are testing a half-fake object.

Java
List<String> real = new ArrayList<>();
List<String> spy = spy(real);

spy.add("one");
doReturn(100).when(spy).size();   // use doReturn with spies, not when(spy.size())

assertEquals(100, spy.size());
assertEquals("one", spy.get(0));  // real behavior

With a spy, when(spy.size()) would call the real size() while recording the stub, which can have side effects or throw. The doReturn(...).when(spy) form avoids the real call. The same form is needed to stub void methods: doThrow(new IOException()).when(mock).close().

Mockito with TestNG

TestNG has no extension model, so the integration is a listener. Add mockito-testng, then register MockitoTestNGListener on the class:

Java
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.testng.MockitoTestNGListener;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners(MockitoTestNGListener.class)
public class OrderServiceNgTest {
    @Mock PaymentGateway gateway;
    @Mock Notifier notifier;
    @InjectMocks OrderService service;

    @Test
    public void paidOrderNotifies() {
        when(gateway.charge("ann", 1250)).thenReturn(true);
        service.place("ann", 1250);
        verify(notifier).send("ann", "Paid 12.50");
    }
}

If you prefer no listener, create the mocks by hand in a setup method with MockitoAnnotations.openMocks(this) inside @BeforeMethod, and close the returned AutoCloseable in @AfterMethod. Listeners and parallel runs are covered in Listeners, Retry and Parallel Execution.

When not to mock

  • Do not mock the class under test; do not mock simple value objects (Money, LocalDate, records). Use real ones.
  • Prefer a hand-written fake (an in-memory repository) when the collaborator has real behavior; fakes survive refactoring better than long when chains.
  • If a test needs five mocks and twenty stubs, the class has too many dependencies. Treat that pain as design feedback.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In when(gateway.charge("ann", 1250)).thenReturn(true), when does the stubbed answer apply?

    A stub is attached to one specific call, so the arguments must match. Other calls fall back to the mock's default answer, for example false for a boolean.
  2. 2. Why does MockitoExtension's strict mode fail a test that stubs a method nobody calls?

    An unused stub is a sign of drift: the implementation changed or the test stubs the wrong arguments. Strictness surfaces that early. Use lenient() only for stubs that are truly optional.
  3. 3. Which form should you use to stub a method on a spy?

    when(spy.method()) calls the real method while recording the stub. doReturn(...).when(spy) sets up the stub without running the real code.
  4. 4. A call uses verify(notifier).send(eq("ann"), captor.capture()). Why is eq("ann") needed?

    Mockito cannot mix raw values and matchers in one call. Wrapping the plain value in eq() keeps the call consistent.

Summary

  • Mockito creates doubles for collaborators: @Mock, @InjectMocks, @Spy and @Captor with MockitoExtension (JUnit) or MockitoTestNGListener (TestNG).
  • when(call).thenReturn(...) stubs one specific call; unstubbed calls return defaults.
  • Assert results first, then verify the calls that matter; use never() and verifyNoInteractions for things that must not happen.
  • Strict stubs fail tests with unused stubs; keep them on.
  • Use ArgumentCaptor to inspect arguments, and remember that matchers must be used for all arguments of a call.
  • Spies wrap real objects; stub them with doReturn(...).when(spy), and treat heavy spy use as a design smell.
  • The lesson's Proxy library shows the mechanism, but real Mockito is what you use in projects.

Next, see how these tests run in a build: Running Tests with Maven and Gradle.