Mocks and test doubles

suggest change

A unit test should check one piece of code by itself. Real code has collaborators, though: a payment gateway, a database, an email server, the system clock. Using the real thing in a test makes the test slow and flaky, and sometimes expensive (you don't want to charge a real credit card on every build).

A test double is an object that stands in for a real collaborator during a test, like a stunt double stands in for an actor. This article covers the different kinds of doubles, how to write them by hand, and how to use Mockito, the standard mocking library for Java.

Kinds of test doubles

The names come from Gerard Meszaros' book xUnit Test Patterns. "Mock" is often used loosely for all of them, but the differences matter when you decide what to use:

Kind What it does Typical use
Dummy Passed around but never used Filling a required constructor parameter
Stub Returns canned answers "The gateway approves every payment"
Spy A stub that also records how it was called "Was an email sent, and to whom?"
Mock Pre-programmed with expectations it verifies "save must be called exactly once"
Fake A working, simplified implementation In-memory repository instead of a database

Stubs and fakes help with state verification: you run the code and then check the result. Mocks and spies support behavior verification: you check which calls the code made to its collaborators.

Code that can be tested with doubles

Doubles only work if the code under test lets you pass them in. That means depending on interfaces and receiving dependencies through the constructor, as described in Dependency injection and Programming to an interface.

All examples in this article use this small order service:

import java.time.Clock;
import java.time.Instant;
import java.util.Optional;

record PaymentResult(boolean approved, String transactionId) {}

record Order(String id, String customerId, long amountCents, Instant createdAt) {}

interface PaymentGateway {
    PaymentResult charge(String customerId, long amountCents);
}

interface OrderRepository {
    void save(Order order);
    Optional<Order> findById(String id);
}

interface EmailSender {
    void send(String to, String subject, String body);
}

class PaymentDeclinedException extends RuntimeException {
    PaymentDeclinedException(String customerId) {
        super("payment declined for " + customerId);
    }
}

class OrderService {
    private final PaymentGateway gateway;
    private final OrderRepository repository;
    private final EmailSender email;
    private final Clock clock;

    OrderService(PaymentGateway gateway, OrderRepository repository,
                 EmailSender email, Clock clock) {
        this.gateway = gateway;
        this.repository = repository;
        this.email = email;
        this.clock = clock;
    }

    Order placeOrder(String customerId, long amountCents) {
        if (amountCents <= 0) {
            throw new IllegalArgumentException("amount must be positive");
        }
        PaymentResult result = gateway.charge(customerId, amountCents);
        if (!result.approved()) {
            throw new PaymentDeclinedException(customerId);
        }
        Order order = new Order("order-" + result.transactionId(), customerId,
                amountCents, Instant.now(clock));
        repository.save(order);
        email.send(customerId, "Order confirmed",
                "Order " + order.id() + " for " + amountCents + " cents");
        return order;
    }
}

Note the Clock parameter. Code that calls Instant.now() directly can't be tested deterministically. Code that calls Instant.now(clock) can, because the test can pass a fixed clock.

Writing doubles by hand

You don't need a library to create test doubles. For small interfaces, a hand-written class or a lambda is often clearer than a mock.

A stub that always returns the same answer:

class StubGateway implements PaymentGateway {
    private final boolean approve;
    private int counter = 0;

    StubGateway(boolean approve) {
        this.approve = approve;
    }

    @Override
    public PaymentResult charge(String customerId, long amountCents) {
        counter++;
        return new PaymentResult(approve, "tx-" + counter);
    }
}

PaymentGateway has a single abstract method, so it is a functional interface and a lambda works too:

PaymentGateway alwaysDecline = (customer, amount) -> new PaymentResult(false, null);

A fake repository that really stores orders, just in memory:

class InMemoryOrderRepository implements OrderRepository {
    private final Map<String, Order> orders = new HashMap<>();

    @Override
    public void save(Order order) {
        orders.put(order.id(), order);
    }

    @Override
    public Optional<Order> findById(String id) {
        return Optional.ofNullable(orders.get(id));
    }
}

A spy that records every email instead of sending it:

record Email(String to, String subject, String body) {}

class RecordingEmailSender implements EmailSender {
    final List<Email> sent = new ArrayList<>();

    @Override
    public void send(String to, String subject, String body) {
        sent.add(new Email(to, subject, body));
    }
}

For the clock, the JDK already ships a double: Clock.fixed always returns the same instant.

Putting it together (save as HandWritten.java together with the classes above, then run java HandWritten.java):

public class HandWritten {
    public static void main(String[] args) {
        var gateway = new StubGateway(true);
        var repo = new InMemoryOrderRepository();
        var email = new RecordingEmailSender();
        var clock = Clock.fixed(Instant.parse("2026-01-15T10:00:00Z"), ZoneOffset.UTC);
        var service = new OrderService(gateway, repo, email, clock);

        Order order = service.placeOrder("alice", 2500);

        System.out.println("order:  " + order);
        System.out.println("stored: " + repo.findById(order.id()).isPresent());
        System.out.println("emails: " + email.sent);

        var declining = new OrderService(
                (customer, amount) -> new PaymentResult(false, null),
                repo, email, clock);
        try {
            declining.placeOrder("bob", 999);
        } catch (PaymentDeclinedException e) {
            System.out.println("error:  " + e.getMessage());
        }
        System.out.println("emails after decline: " + email.sent.size());
    }
}
order:  Order[id=order-tx-1, customerId=alice, amountCents=2500, createdAt=2026-01-15T10:00:00Z]
stored: true
emails: [Email[to=alice, subject=Order confirmed, body=Order order-tx-1 for 2500 cents]]
error:  payment declined for bob
emails after decline: 1

(HandWritten must be the first class in the file, and the file needs import java.time.*; and import java.util.*;.)

Hand-written doubles are type-checked by the compiler, survive refactoring well, and are easy to read. Their downside is boilerplate when an interface has many methods. That is where a mocking library helps.

Setting up Mockito

Add Mockito and JUnit to your build. mockito-junit-jupiter brings in mockito-core and adds the JUnit 5 extension:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.13.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>5.20.0</version>
    <scope>test</scope>
</dependency>

For Gradle:

testImplementation 'org.junit.jupiter:junit-jupiter:5.13.4'
testImplementation 'org.mockito:mockito-junit-jupiter:5.20.0'

Mockito 5 requires Java 11 or newer. It uses the inline mock maker by default, which can mock final classes and methods and static methods (more on that below). Newer versions of both libraries work the same way. JUnit 6 is fine as well.

On JDK 21 and newer you'll see a warning that Mockito is "self-attaching" a Java agent, because dynamic agent loading is being phased out (JEP 451). The fix is to load Mockito as an agent explicitly. With Maven:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <goals><goal>properties</goal></goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <argLine>@{argLine} -javaagent:${org.mockito:mockito-core:jar}</argLine>
    </configuration>
</plugin>

If nothing else (such as JaCoCo) sets argLine, drop the @{argLine} part.

Creating a mock and stubbing it

mock(Type.class) creates an object that implements the type. Every method does nothing and returns a default value: null for objects, 0 / false for primitives, and empty values for Optional, Stream and collections.

when(...).thenReturn(...) stubs a method, i.e. tells it what to return for given arguments:

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

import java.time.*;
import org.junit.jupiter.api.Test;

class OrderServiceTest {
    Clock clock = Clock.fixed(Instant.parse("2026-01-15T10:00:00Z"), ZoneOffset.UTC);

    @Test
    void placesOrderWhenPaymentIsApproved() {
        PaymentGateway gateway = mock(PaymentGateway.class);
        OrderRepository repo = mock(OrderRepository.class);
        EmailSender email = mock(EmailSender.class);
        when(gateway.charge("alice", 2500)).thenReturn(new PaymentResult(true, "tx-42"));

        var service = new OrderService(gateway, repo, email, clock);
        Order order = service.placeOrder("alice", 2500);

        assertEquals("order-tx-42", order.id());
        assertEquals(Instant.parse("2026-01-15T10:00:00Z"), order.createdAt());
    }
}

The call gateway.charge("alice", 2500) inside when(...) is not a real call. Mockito records it as "the invocation being stubbed". If the code under test later calls charge with different arguments, the mock returns the default (null here).

More stubbing options:

// different values on consecutive calls; the last one repeats
when(gateway.charge(anyString(), anyLong()))
        .thenReturn(new PaymentResult(false, null))
        .thenReturn(new PaymentResult(true, "tx-1"));

// throw an exception
when(gateway.charge("mallory", 100)).thenThrow(new IllegalStateException("gateway down"));

// compute the answer from the arguments
when(gateway.charge(anyString(), anyLong())).thenAnswer(invocation -> {
    long amount = invocation.getArgument(1);
    return new PaymentResult(amount < 10_000, "tx-" + amount);
});

when(...) needs a return value, so it can't be used with void methods. For those, use the do... family:

doThrow(new RuntimeException("SMTP down"))
        .when(email).send(anyString(), anyString(), anyString());

Argument matchers

Instead of exact values you can use matchers from org.mockito.ArgumentMatchers (also reachable through Mockito.*): any(), any(Order.class), anyString(), anyLong(), eq(value), startsWith("x"), contains("x"), isNull(), notNull(), and argThat(predicate) for custom checks.

when(gateway.charge(startsWith("vip-"), longThat(a -> a > 0)))
        .thenReturn(new PaymentResult(true, "vip-tx"));

There is one rule that trips up everybody: if one argument uses a matcher, all arguments must. Wrap literal values in eq():

when(gateway.charge("alice", anyLong()));        // InvalidUseOfMatchersException
when(gateway.charge(eq("alice"), anyLong()));    // correct

Use longThat, intThat etc. for primitive parameters. argThat returns null, which causes a NullPointerException when the parameter is a primitive long.

Verifying interactions

Stubbing controls what goes into the code under test. verify checks what comes out as calls to collaborators:

@Test
void savesOrderAndSendsConfirmation() {
    PaymentGateway gateway = mock(PaymentGateway.class);
    OrderRepository repo = mock(OrderRepository.class);
    EmailSender email = mock(EmailSender.class);
    when(gateway.charge("alice", 2500)).thenReturn(new PaymentResult(true, "tx-42"));

    Order order = new OrderService(gateway, repo, email, clock).placeOrder("alice", 2500);

    verify(repo).save(order);
    verify(email).send(eq("alice"), eq("Order confirmed"), contains("order-tx-42"));
}

verify(mock).method(args) means "called exactly once with these arguments". Other counts:

verify(gateway, times(2)).charge(anyString(), anyLong());
verify(email, never()).send(anyString(), anyString(), anyString());
verify(repo, atLeastOnce()).save(any());
verify(repo, atMost(3)).save(any());
verifyNoInteractions(repo, email);   // no method was called at all
verifyNoMoreInteractions(gateway);   // every call has already been verified

When verification fails, Mockito explains what it expected and what actually happened:

Argument(s) are different! Wanted:
emailSender.send(
    "alice",
    "Order confirmed",
    contains("order-tx-99")
);
-> at OrderServiceTest.savesOrderAndSendsConfirmation(OrderServiceTest.java:...)
Actual invocations have different arguments at position [2]:
emailSender.send(
    "alice",
    "Order confirmed",
    "Order order-tx-42 for 2500 cents"
);
-> at OrderService.placeOrder(OrderService.java:...)

Testing the failure path uses verifyNoInteractions:

@Test
void declinedPaymentStoresNothing() {
    PaymentGateway gateway = mock(PaymentGateway.class);
    OrderRepository repo = mock(OrderRepository.class);
    EmailSender email = mock(EmailSender.class);
    when(gateway.charge("bob", 999)).thenReturn(new PaymentResult(false, null));

    var service = new OrderService(gateway, repo, email, clock);

    assertThrows(PaymentDeclinedException.class, () -> service.placeOrder("bob", 999));
    verifyNoInteractions(repo, email);
}

To check the order of calls across mocks, use InOrder:

InOrder inOrder = inOrder(gateway, repo, email);
inOrder.verify(gateway).charge("alice", 2500);
inOrder.verify(repo).save(any());
inOrder.verify(email).send(anyString(), anyString(), anyString());

Capturing arguments

Sometimes the object passed to a collaborator is created inside the code under test, so you can't build an equal one in the test. ArgumentCaptor grabs it so you can assert on its fields:

ArgumentCaptor<Order> captor = ArgumentCaptor.forClass(Order.class);
verify(repo).save(captor.capture());

Order saved = captor.getValue();
assertEquals("alice", saved.customerId());
assertEquals(2500, saved.amountCents());

If the method was called several times, captor.getAllValues() returns a list of all captured arguments.

Annotations and the JUnit extension

Creating mocks by hand in every test gets repetitive. With MockitoExtension, fields annotated with @Mock are created fresh before each test:

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

import java.time.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class OrderServiceAnnotatedTest {
    static final Instant NOW = Instant.parse("2026-01-15T10:00:00Z");

    @Mock PaymentGateway gateway;
    @Mock OrderRepository repo;
    @Mock EmailSender email;
    @Captor ArgumentCaptor<Order> orderCaptor;

    OrderService service;

    @BeforeEach
    void setUp() {
        service = new OrderService(gateway, repo, email, Clock.fixed(NOW, ZoneOffset.UTC));
    }

    @Test
    void savesOrderWithTimestampFromClock() {
        when(gateway.charge("alice", 2500)).thenReturn(new PaymentResult(true, "tx-1"));

        service.placeOrder("alice", 2500);

        verify(repo).save(orderCaptor.capture());
        assertEquals(NOW, orderCaptor.getValue().createdAt());
    }

    @Test
    void rejectsZeroAmount() {
        assertThrows(IllegalArgumentException.class, () -> service.placeOrder("alice", 0));
        verifyNoInteractions(gateway);
    }
}

@Captor creates a properly typed ArgumentCaptor<Order> without the unchecked-cast warning you'd get for generic types like ArgumentCaptor<List<Order>>.

Mockito also has @InjectMocks, which builds the object under test by passing the @Mock fields to its biggest constructor, matched by type:

@Mock PaymentGateway gateway;
@Mock OrderRepository repo;
@Mock EmailSender email;
@InjectMocks OrderService service;   // Clock parameter gets null!

The catch: when no mock matches a constructor parameter, Mockito silently passes null. Here the Clock would be null and placeOrder would throw a NullPointerException. Mockito also falls back to setter and field injection without telling you which strategy it used. An explicit constructor call in @BeforeEach, as above, is one line longer and never surprising.

Strict stubs

MockitoExtension runs in strict stubs mode by default. It fails a test that stubs a method the code never calls. Suppose rejectsZeroAmount above started with when(gateway.charge(anyString(), anyLong())).thenReturn(...). The service throws before reaching the gateway, so the test fails with:

org.mockito.exceptions.misusing.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 OrderServiceAnnotatedTest.rejectsZeroAmount(OrderServiceAnnotatedTest.java:39)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.

This is useful: leftover stubs make tests misleading. It also reports PotentialStubbingProblem when the code calls a stubbed method with different arguments than the stub, which usually signals a bug in the test or in the code.

If a stub really is optional (for example, shared setup in @BeforeEach that some tests don't use), mark it as lenient:

lenient().when(gateway.charge(anyString(), anyLong()))
        .thenReturn(new PaymentResult(true, "tx-default"));

Spies: partial mocks of real objects

spy(object) wraps a real object. Calls go to the real methods unless you stub them, and every call is recorded for verify:

List<String> list = spy(new ArrayList<>());
list.add("one");
list.add("two");

verify(list).add("one");
assertEquals(2, list.size());   // real method

doReturn(100).when(list).size();
assertEquals(100, list.size()); // stubbed

For spies, always stub with doReturn(...).when(spy).method(), not when(spy.method()). The latter calls the real method while stubbing:

List<String> list = spy(new ArrayList<>());
when(list.get(0)).thenReturn("x");   // IndexOutOfBoundsException: real get(0) runs
doReturn("x").when(list).get(0);     // correct

Needing a spy is often a sign that a class does too much. Use spies mainly with legacy code you can't refactor yet.

Mocking final classes and static methods

Since Mockito 5 the inline mock maker is the default, so final classes, final methods and records can be mocked like any other type.

Static methods can be mocked with mockStatic. The mock is active only inside the try-with-resources block and only on the current thread:

class IdGenerator {
    static String next() {
        return java.util.UUID.randomUUID().toString();
    }
}

@Test
void staticMock() {
    try (MockedStatic<IdGenerator> ids = mockStatic(IdGenerator.class)) {
        ids.when(IdGenerator::next).thenReturn("fixed-id");

        assertEquals("fixed-id", IdGenerator.next());
        ids.verify(IdGenerator::next);
    }
    assertNotEquals("fixed-id", IdGenerator.next()); // real method again
}

Similarly, mockConstruction(Foo.class) makes every new Foo(...) inside the block return a mock. Both are escape hatches for code you can't change. If you own the code, inject the dependency instead, as OrderService does with Clock. Avoid mocking JDK classes such as Instant or System. Mockito refuses some of them, and it's fragile even where it works.

BDD style

BDDMockito provides aliases that read better in given / when / then tests. They behave exactly like when and verify:

import static org.mockito.BDDMockito.*;

// given
given(gateway.charge("alice", 2500)).willReturn(new PaymentResult(true, "tx-1"));
// when
service.placeOrder("alice", 2500);
// then
then(repo).should().save(any(Order.class));
then(email).should(never()).send(eq("bob"), anyString(), anyString());

How mocks work under the hood

A mock is just an object whose methods are generated at runtime and route every call to a handler. For interfaces you can build a toy version with the JDK's Dynamic Proxies:

import java.lang.reflect.Proxy;
import java.util.*;

public class ToyMock {
    interface EmailSender {
        void send(String to, String subject, String body);
    }

    @SuppressWarnings("unchecked")
    static <T> T recorder(Class<T> type, List<String> calls) {
        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type},
                (proxy, method, args) -> {
                    calls.add(method.getName() + Arrays.toString(args));
                    return null;
                });
    }

    public static void main(String[] args) {
        List<String> calls = new ArrayList<>();
        EmailSender email = recorder(EmailSender.class, calls);
        email.send("alice", "Hi", "Hello there");
        email.send("bob", "Hi", "Hey");
        System.out.println(calls);
    }
}
[send[alice, Hi, Hello there], send[bob, Hi, Hey]]

Mockito does the same thing with much more machinery: it generates subclasses (or rewrites the bytecode of existing classes with the inline mock maker) using Byte Buddy, so it also works for concrete and final classes.

When to use which double

Common pitfalls

For an introduction to unit testing in general, see What is Unit Testing. To run the same test with many inputs, see Parameterized tests.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents