Skip to lesson

@Mock, @InjectMocks and when/thenReturn

In the last lesson you wrote about 50 lines of doubles by hand for one service. Mockito creates each double in one line and lets every test choose its own answers.

The mockito-junit-jupiter dependency and MockitoExtension

MockitoExtension is the JUnit 5 extension, switched on with @ExtendWith(MockitoExtension.class), that creates fresh mocks before each test and checks for stubbing mistakes after it.

Add Mockito to a plain Maven project with one dependency in test scope.

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

Example 1 · mvn test on JDK 21: Mockito's agent warning

Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)

Terminal
mvn test
Sample output
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.shoplite.lab.OrderServiceTest
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 (C:\Users\asha\.m2\repository\net\bytebuddy\byte-buddy-agent\1.17.7\byte-buddy-agent-1.17.7.jar)
WARNING: If a serviceability tool is in use, please run with -XX:+EnableDynamicAgentLoading to hide this warning
WARNING: If a serviceability tool is not in use, please run with -Djdk.instrument.traceUsage for more information
WARNING: Dynamic loading of agents will be disallowed by default in a future release
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.214 s -- in com.shoplite.lab.OrderServiceTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

What this code does

  • The first line comes from Mockito: on JDK 21+ it attaches its byte-code agent at run time and warns that future JDKs will block this.
  • The four WARNING lines come from the JVM about the same agent. The tests themselves ran and passed: 3 run, 0 failures, 0 errors.

mockito-junit-jupiter is the Maven artifact that brings Mockito (mockito-core) and the extension. Test scope keeps it out of the jar. This course uses 5.23.0.

In shoplite-api you add nothing: the Spring Boot test starters already bring Mockito, and Boot 4.1.1 picks the version (5.23.0).

On JDK 21 and later, Mockito 5 prints a warning that it is "self-attaching" an agent. Tests still pass; Mockito's documentation shows how to pass it as a -javaagent in Surefire's argLine to silence it. shoplite-api runs on Java 17, where the warning does not appear.

@Mock, @InjectMocks and Mockito.mock()

A mock is an object that Mockito generates at run time. It implements a type, records every call and returns what the test stubbed.

@Mock makes a mock and @InjectMocks builds the class under test. The same set-up written by hand:

Java
// The same set-up without annotationsProductRepository products = mock(ProductRepository.class);OrderRepository orders = mock(OrderRepository.class);PaymentGateway payments = mock(PaymentGateway.class);EmailSender emails = mock(EmailSender.class);OrderService service = new OrderService(products, orders, payments, emails);

Example 2 · src/test/java/com/shoplite/lab/OrderServiceTest.java

Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)

Java
package com.shoplite.lab;
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.Mockito.when;
import java.math.BigDecimal;import java.util.Optional;
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    ProductRepository products;    @Mock    OrderRepository orders;    @Mock    PaymentGateway payments;    @Mock    EmailSender emails;
    @InjectMocks    OrderService service;   // built with the four mocks above
    @Test    void placeOrder_returnsTheSavedOrder() {        when(products.findById(9))                .thenReturn(Optional.of(new Product(9, "Clean Code", new BigDecimal("499.00"), 30)));        when(payments.charge(1, new BigDecimal("998.00"))).thenReturn("pay_501");        when(orders.save(any(Order.class)))                .thenReturn(new Order(17, 1, 9, 2, new BigDecimal("998.00"), "pay_501"));
        Order order = service.placeOrder(1, 9, 2);
        assertEquals(17, order.id());        assertEquals("pay_501", order.paymentId());    }
    @Test    void placeOrder_unknownProduct_throws() {        // no stubbing: findById returns Optional.empty() by default
        ProductNotFoundException e = assertThrows(ProductNotFoundException.class,                () -> service.placeOrder(1, 99, 1));
        assertEquals("Product 99 does not exist.", e.getMessage());    }
    @Test    void placeOrder_moreThanInStock_throws() {        when(products.findById(3))                .thenReturn(Optional.of(new Product(3, "iPhone 15 128GB", new BigDecimal("69900.00"), 8)));
        OutOfStockException e = assertThrows(OutOfStockException.class,                () -> service.placeOrder(2, 3, 9));
        assertEquals("Only 8 units of iPhone 15 128GB are in stock; 9 were requested.", e.getMessage());    }}
Sample output
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.shoplite.lab.OrderServiceTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.912 s -- in com.shoplite.lab.OrderServiceTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

What this code does

  • Four @Mock fields and one @InjectMocks field: before each test, Mockito creates new mocks and calls the four-argument OrderService constructor with them.
  • The happy path stubs three calls and checks what placeOrder returned. The unknown-product test stubs nothing: findById(99) returns Optional.empty() by default.
  • The out-of-stock test stubs only findById(3); the service throws before it reaches the gateway, so nothing else is needed.

@InjectMocks picks the biggest constructor and matches each parameter to a mock by type.

The same can be written by hand: mock(PaymentGateway.class) returns a mock, and you call new OrderService(...) yourself, usually in a @BeforeEach method. Both styles are fine. The annotations are shorter; the manual style shows the wiring openly. One trap: if a constructor parameter has no matching @Mock, @InjectMocks quietly passes null. Forget @Mock EmailSender emails and placeOrder meets a NullPointerException at the email step.

when(...).thenReturn(...) and default answers

Stubbing means telling a mock what to return for a call: when(call).thenReturn(value).

when(products.findById(9)).thenReturn(Optional.of(cleanCode)) reads as a sentence. The example builds a tiny mock maker to show how a mock chooses its answer.

Example 3 · A tiny mock maker: stubbed answers and defaults

TinyMockDemo.javaJava
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.math.BigDecimal;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;
record Product(int id, String name, BigDecimal price, int stock) {}
interface ProductRepository {    Optional<Product> findById(int id);
    int countInStock();
    boolean exists(int id);}
interface PaymentGateway {    String charge(int customerId, BigDecimal amount);}
interface OrderRepository {    List<String> findByCustomer(int customerId);}
/** A very small mock maker: answers stubbed calls, everything else gets a default value. */class TinyMock implements InvocationHandler {    private final Map<String, Object> answers = new HashMap<>();    private final String name;
    private TinyMock(String name) {        this.name = name;    }
    @SuppressWarnings("unchecked")    static <T> T mock(Class<T> type) {        TinyMock handler = new TinyMock(type.getSimpleName());        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, handler);    }
    static TinyMock of(Object mock) {        return (TinyMock) Proxy.getInvocationHandler(mock);    }
    /** Like when(mock.method(args)).thenReturn(value), with the call written as text. */    void stub(String call, Object value) {        answers.put(call, value);    }
    @Override    public Object invoke(Object proxy, Method method, Object[] args) {        if (method.getName().equals("toString")) {            return "TinyMock for " + name;        }        String call = method.getName() + Arrays.toString(args == null ? new Object[0] : args);        if (answers.containsKey(call)) {            return answers.get(call);        }        return defaultFor(method.getReturnType());    }
    private static Object defaultFor(Class<?> type) {        if (type == int.class) return 0;        if (type == boolean.class) return false;        if (type == Optional.class) return Optional.empty();        if (type == List.class) return List.of();        return null;                                   // String, BigDecimal, records, ...    }}
public class TinyMockDemo {    public static void main(String[] args) {        ProductRepository products = TinyMock.mock(ProductRepository.class);        PaymentGateway payments = TinyMock.mock(PaymentGateway.class);        OrderRepository orders = TinyMock.mock(OrderRepository.class);
        System.out.println("Before stubbing (default answers):");        System.out.println("  findById(9)       -> " + products.findById(9));        System.out.println("  countInStock()    -> " + products.countInStock());        System.out.println("  exists(9)         -> " + products.exists(9));        System.out.println("  charge(1, 998.00) -> " + payments.charge(1, new BigDecimal("998.00")));        System.out.println("  findByCustomer(1) -> " + orders.findByCustomer(1));
        TinyMock.of(products).stub("findById[9]",                Optional.of(new Product(9, "Clean Code", new BigDecimal("499.00"), 30)));        TinyMock.of(payments).stub("charge[1, 998.00]", "pay_501");
        System.out.println("After stubbing:");        System.out.println("  findById(9)       -> " + products.findById(9));        System.out.println("  findById(3)       -> " + products.findById(3));        System.out.println("  charge(1, 998.00) -> " + payments.charge(1, new BigDecimal("998.00")));        System.out.println("  charge(1, 998)    -> " + payments.charge(1, new BigDecimal("998")));        System.out.println("  toString          -> " + payments);    }}
Output
Before stubbing (default answers):
  findById(9)       -> Optional.empty
  countInStock()    -> 0
  exists(9)         -> false
  charge(1, 998.00) -> null
  findByCustomer(1) -> []
After stubbing:
  findById(9)       -> Optional[Product[id=9, name=Clean Code, price=499.00, stock=30]]
  findById(3)       -> Optional.empty
  charge(1, 998.00) -> pay_501
  charge(1, 998)    -> null
  toString          -> TinyMock for PaymentGateway

What this code does

  • Proxy.newProxyInstance creates an object that implements the interface and sends every call to invoke. That method looks up a stubbed answer by method name and arguments, or returns a default.
  • Before stubbing, every call gets the defaults Mockito also uses: Optional.empty, 0, false, null and an empty list.
  • charge(1, 998) is not the stubbed charge(1, 998.00), so it gets null. Mockito compares arguments with equals, and BigDecimal counts 998 and 998.00 as different.

Mockito compares the arguments with equals, so findById(3) is a different call from findById(9).

A call that was not stubbed gets a default answer: null for objects such as String and BigDecimal, 0 for numbers, false for boolean, an empty collection for List or Set, and Optional.empty() for Optional. That is why findById(99) needs no stubbing to test "product not found".

Order of execution

Order the steps of a Mockito test

Tap the steps in the order they happen.

Argument matchers and the all-or-nothing rule

An argument matcher stands for "any value that fits" instead of one exact value: any(), anyInt(), anyString(), or eq(x) for one exact value.

A matcher says "any value" or "exactly this value". Mixing a matcher with a raw value breaks the call, as the output shows.

Example 4 · Mixing a matcher with a raw value

Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)

Java
// src/test/java/com/shoplite/lab/StubbingMistakesTest.java (part)// Same @Mock fields and @InjectMocks OrderService as OrderServiceTest.
@Testvoid mixesMatchersAndRawValues() {    when(products.findById(9))            .thenReturn(Optional.of(new Product(9, "Clean Code", new BigDecimal("499.00"), 30)));    when(payments.charge(anyInt(), new BigDecimal("998.00"))).thenReturn("pay_501");   // wrong
    service.placeOrder(1, 9, 2);}
@Testvoid allMatchers() {    when(products.findById(9))            .thenReturn(Optional.of(new Product(9, "Clean Code", new BigDecimal("499.00"), 30)));    when(payments.charge(anyInt(), eq(new BigDecimal("998.00")))).thenReturn("pay_501");    when(orders.save(any(Order.class))).thenReturn(new Order(17, 1, 9, 2, new BigDecimal("998.00"), "pay_501"));
    assertEquals(17, service.placeOrder(1, 9, 2).id());}
Sample output
[ERROR] Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.958 s <<< FAILURE! -- in com.shoplite.lab.StubbingMistakesTest
[ERROR] com.shoplite.lab.StubbingMistakesTest.mixesMatchersAndRawValues -- Time elapsed: 0.012 s <<< ERROR!
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at com.shoplite.lab.StubbingMistakesTest.mixesMatchersAndRawValues(StubbingMistakesTest.java:40)

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.

	at com.shoplite.lab.StubbingMistakesTest.mixesMatchersAndRawValues(StubbingMistakesTest.java:40)

What this code does

  • charge has two parameters, so Mockito expected two matchers but recorded one (anyInt()): the BigDecimal was a raw value.
  • The fix wraps it: eq(new BigDecimal("998.00")). Now both arguments are matchers and the second test passes.

The rule is all or nothing: if one argument of a call uses a matcher, every argument must. charge(anyInt(), new BigDecimal("998.00")) mixes a matcher with a raw value and fails with InvalidUseOfMatchersException. Wrap the raw value in eq(...), or use raw values everywhere.

Prefer exact values when the value matters, such as the amount charged. Use any(...) when it does not, such as the whole Order passed to save. Matchers are static methods of org.mockito.ArgumentMatchers.

Fix the error

Fix the verify line

Read the error, then pick the line that fixes it.

This verify throws the error below. Replace line 2.

when(products.findById(anyInt())).thenReturn(Optional.of(cleanCode));
verify(emails).sendOrderConfirmation(1, anyInt(), any(BigDecimal.class));

Error

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 2 recorded:

Strict stubs: unused or mismatched stubbings fail

Strict stubs are the default of MockitoExtension: an unused stubbing fails with UnnecessaryStubbingException, and a stubbed method called with other arguments fails with PotentialStubbingProblem.

Two stubbing mistakes that Mockito catches for you: one stubbing never used, one stubbed with the wrong argument.

Example 5 · Strict stubs catch an unused and a mismatched stubbing

Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)

Java
// src/test/java/com/shoplite/lab/StubbingMistakesTest.java (part)
@Testvoid stubNeverUsed() {    when(products.findById(3))            .thenReturn(Optional.of(new Product(3, "iPhone 15 128GB", new BigDecimal("69900.00"), 8)));    when(payments.charge(2, new BigDecimal("629100.00"))).thenReturn("pay_502");   // never reached
    assertThrows(OutOfStockException.class, () -> service.placeOrder(2, 3, 9));}
@Testvoid stubWithDifferentArgument() {    when(products.findById(9))            .thenReturn(Optional.of(new Product(9, "Clean Code", new BigDecimal("499.00"), 30)));    when(payments.charge(1, new BigDecimal("998"))).thenReturn("pay_501");   // 998 is not 998.00
    service.placeOrder(1, 9, 2);}
Sample output
[ERROR] com.shoplite.lab.StubbingMistakesTest.stubNeverUsed -- Time elapsed: 0.009 s <<< ERROR!
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 com.shoplite.lab.StubbingMistakesTest.stubNeverUsed(StubbingMistakesTest.java:59)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.

[ERROR] com.shoplite.lab.StubbingMistakesTest.stubWithDifferentArgument -- Time elapsed: 0.004 s <<< ERROR!
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
 - this invocation of 'charge' method:
    payments.charge(1, 998.00);
    -> at com.shoplite.lab.OrderService.placeOrder(OrderService.java:30)
 - has following stubbing(s) with different arguments:
    1. payments.charge(1, 998); stubbed with: [Returns: pay_501]
      -> at com.shoplite.lab.StubbingMistakesTest.stubWithDifferentArgument(StubbingMistakesTest.java:68)
Typically, stubbing argument mismatch indicates user mistake when writing tests.
Mockito fails early so that you can debug potential problem easily.
...

What this code does

  • stubNeverUsed: the service throws OutOfStockException before charging, so the charge stubbing on line 59 is never used. Fix: delete it.
  • stubWithDifferentArgument: the service charged 998.00 (499.00 × 2 keeps two decimals) but the stub says 998. Fix: stub the exact value the code passes, new BigDecimal("998.00").
  • Without strict stubs the second test would get null as the payment id and might still pass, hiding the mismatch.

Both catch real mistakes. A leftover stubbing makes the test lie about what the code needs. A mismatch usually means the code computed a different value than you expected, such as 998.00 against 998. BigDecimal.equals compares the scale too, so those two are different arguments.

Fix the test, not the strictness. When a stubbing really is shared by tests that do not all use it, mark only that one with lenient().when(...).

@MockitoSettings(strictness = Strictness.LENIENT) turns strictness off for a whole class. It hides the same mistakes it silences, so use it rarely.

Next step

Check your understanding

12 quick questions