Skip to lesson

Practice: Mockito

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Four habits cause most Mockito failures: mixing matchers with raw values, stubbing calls the code never makes, using when where only doThrow works, and mocking too much. Each has a short fix.

Mistake 1: mixing matchers and raw values

A captor is a matcher too, so one raw value next to capture() breaks the call.

Example 1 · Mistake: a captor mixed with raw values

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

Java
// Wrong: a captor is a matcher, so 1 and 17 are raw values mixed with itverify(emails).sendOrderConfirmation(1, 17, totalCaptor.capture());
// Wrong: same rule in stubbingwhen(payments.charge(anyInt(), new BigDecimal("998.00"))).thenReturn("pay_501");
// Right: all matchers...verify(emails).sendOrderConfirmation(eq(1), eq(17), totalCaptor.capture());when(payments.charge(anyInt(), eq(new BigDecimal("998.00")))).thenReturn("pay_501");

when(payments.charge(1, new BigDecimal("998.00"))).thenReturn("pay_501");
Sample output (the first verify line)
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 1 recorded:
-> at com.shoplite.lab.OrderServiceVerifyTest.placeOrder_emailsTheComputedTotal(OrderServiceVerifyTest.java:94)

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.

What this code does

  • sendOrderConfirmation has three parameters, so Mockito expected three matchers; only the captor was recorded because 1 and 17 were raw values.
  • eq(1) and eq(17) make all three arguments matchers. The stubbing line has the same problem and the same fix.

If one argument of a call uses a matcher (any(), anyInt(), eq(...) or a captor's capture()), every argument must. The error is InvalidUseOfMatchersException, and its first lines say how many matchers were expected and how many were recorded.

The rule applies in when(...) and in verify(...) alike, and a captor counts as a matcher. The fix is always the same: wrap the raw values in eq(...), or drop the matchers and use raw values everywhere. Review: Argument matchers (opens in a new tab).

Mistake 2: stubbing that does not match the code

Stubs fail in two ways: they do not match the call, or the call was never stubbed. The first example writes the stubbing rules out in plain Java.

Example 2 · Predict the answer: the rules of a stub in plain Java

StubAnswersDemo.javaJava
import java.math.BigDecimal;import java.util.HashMap;import java.util.List;import java.util.Map;
interface PaymentGateway {    String charge(int customerId, BigDecimal amount);}
/** The rules a Mockito stub follows, written out by hand. */class StubbedGateway implements PaymentGateway {    private final Map<String, List<String>> answers = new HashMap<>();    private final Map<String, Integer> callsSoFar = new HashMap<>();
    /** Like when(charge(c, a)).thenReturn(v1, v2, ...): a new stubbing replaces an old one. */    void when(int customerId, BigDecimal amount, String... values) {        answers.put(key(customerId, amount), List.of(values));        callsSoFar.put(key(customerId, amount), 0);    }
    public String charge(int customerId, BigDecimal amount) {        List<String> list = answers.get(key(customerId, amount));        if (list == null) {            return null;                                     // the default answer for a String        }        int n = callsSoFar.merge(key(customerId, amount), 1, Integer::sum) - 1;        return list.get(Math.min(n, list.size() - 1));       // answers in turn, the last repeats    }
    private static String key(int customerId, BigDecimal amount) {        return customerId + "/" + amount;                    // BigDecimal: 998 and 998.00 differ    }}
public class StubAnswersDemo {    public static void main(String[] args) {        StubbedGateway payments = new StubbedGateway();        BigDecimal total = new BigDecimal("998.00");
        payments.when(1, total, "pay_501");        System.out.println("1. charge(1, 998.00) -> " + payments.charge(1, total));        System.out.println("2. charge(1, 998)    -> " + payments.charge(1, new BigDecimal("998")));        System.out.println("3. charge(2, 998.00) -> " + payments.charge(2, total));
        payments.when(1, total, "pay_777");        System.out.println("4. charge(1, 998.00) -> " + payments.charge(1, total));
        payments.when(1, total, "pay_601", "pay_602");        System.out.println("5. charge(1, 998.00) -> " + payments.charge(1, total));        System.out.println("6. charge(1, 998.00) -> " + payments.charge(1, total));        System.out.println("7. charge(1, 998.00) -> " + payments.charge(1, total));    }}
Output
1. charge(1, 998.00) -> pay_501
2. charge(1, 998)    -> null
3. charge(2, 998.00) -> null
4. charge(1, 998.00) -> pay_777
5. charge(1, 998.00) -> pay_601
6. charge(1, 998.00) -> pay_602
7. charge(1, 998.00) -> pay_602

What this code does

  • Lines 2 and 3 get null, the default: 998 is not 998.00 for BigDecimal.equals, and customer 2 was never stubbed.
  • Line 4: stubbing the same call again replaced pay_501 with pay_777.
  • Lines 5 to 7: a chain gives its answers in turn and repeats the last one, exactly as thenReturn("pay_601", "pay_602") does in Mockito.

Example 3 · Mistake: a forgotten stub fails far from the cause

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

Java
// src/test/java/com/shoplite/lab/ForgotStubTest.java (part)
@Testvoid 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");    // forgot: when(orders.save(any(Order.class))).thenReturn(...)
    service.placeOrder(1, 9, 2);}
// The fix that also makes the test meaningful:when(orders.save(any(Order.class))).thenAnswer(call -> call.<Order>getArgument(0).withId(17));
Sample output
[ERROR] com.shoplite.lab.ForgotStubTest.placeOrder_returnsTheSavedOrder -- Time elapsed: 0.014 s <<< ERROR!
java.lang.NullPointerException: Cannot invoke "com.shoplite.lab.Order.id()" because "saved" is null
	at com.shoplite.lab.OrderService.placeOrder(OrderService.java:37)
	at com.shoplite.lab.ForgotStubTest.placeOrder_returnsTheSavedOrder(ForgotStubTest.java:36)

What this code does

  • save was not stubbed, so it returned null. The email line threw a NullPointerException, the service's catch then called saved.id() again on line 37 and threw a second one, which reached the test.
  • The helpful message names the variable (saved), which points back to save. thenAnswer returning the passed order with an id fixes it and keeps the test honest.

A stub must match what the code really calls, with equals-equal arguments. A stubbing the code never uses fails with UnnecessaryStubbingException; one with other arguments fails with PotentialStubbingProblem. BigDecimal("998") and BigDecimal("998.00") are different arguments.

The opposite mistake is a call you forgot to stub. It returns the default, often null, and the code fails far from the cause with a NullPointerException. When a test dies inside the service, first check which mock returned null. To predict what a stubbed mock returns, follow four rules: exact match by equals, else the default answer; a new stubbing of the same call replaces the old one; chained answers are used in turn; the last answer repeats. Review: Strict stubs (opens in a new tab).

Mistake 3: when() on void methods and on spies

when(...) runs the call while stubbing. That breaks for void methods and for spies.

Example 4 · Mistakes: void methods, spies and stubbing twice

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

Java
// 1. void method: when(...) does not compile ('void' type not allowed here)when(emails.sendOrderConfirmation(anyInt(), anyInt(), any())).thenThrow(new IllegalStateException("SMTP down"));doThrow(new IllegalStateException("SMTP down")).when(emails).sendOrderConfirmation(anyInt(), anyInt(), any());
// 2. spy: when(...) runs the real get(0) first -> IndexOutOfBoundsExceptionList<String> names = spy(new ArrayList<String>());when(names.get(0)).thenReturn("Ravi");doReturn("Ravi").when(names).get(0);
// 3. stubbing the same call twice: the last one winswhen(payments.charge(1, total)).thenReturn("pay_501");when(payments.charge(1, total)).thenReturn("pay_777");when(payments.charge(1, total)).thenReturn("pay_501", "pay_777");
What each wrong line does
1. compile error: 'void' type not allowed here
2. java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
3. charge(1, total) returns pay_777 every time; with the chain: pay_501, then pay_777

What this code does

  • Cases 1 and 2 break because when(...) needs the call to run and return a value; the do-family names the mock first and never runs the call while stubbing.
  • Case 3 is not an error at all, which makes it worse: the first stubbing is silently replaced.

when(mock.call()) needs the call to return a value, and it runs the call while stubbing. Two cases break that. A void method has no value, so when(emails.sendOrderConfirmation(...)) does not compile. A spy runs its real method, so when(spy.get(0)) can throw before stubbing happens.

Both have the same fix: the do-family, doThrow(...), doReturn(...), doNothing() or doAnswer(...), followed by .when(mock).call(). Also watch for stubbing one call twice: the second when replaces the first, so chain the answers instead. Review: thenThrow and doThrow (opens in a new tab).

Mistake 4: mocking and verifying too much

A test can pass today and still be wrong. Compare an over-mocked test with a focused one.

Example 5 · Mistake: an over-mocked test and its focused rewrite

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

Java
// Over-mocked: a mocked record, a lookup counted, every call in order, nothing else allowedProduct product = mock(Product.class);when(product.price()).thenReturn(new BigDecimal("499.00"));when(product.stock()).thenReturn(30);...inOrder.verify(products, times(1)).findById(9);inOrder.verify(products).updateStock(9, 28);verifyNoMoreInteractions(products, payments, orders, emails);
// Focused: a real record, fakes for our repositories, verify only outside effectsInMemoryProductRepository products = new InMemoryProductRepository(new Product(9, "Clean Code", new BigDecimal("499.00"), 30));...Order order = service.placeOrder(1, 9, 2);assertEquals(28, products.findById(9).orElseThrow().stock());assertEquals(List.of(order), orders.findByCustomer(1));verify(payments).charge(1, new BigDecimal("998.00"));verify(emails).sendOrderConfirmation(1, order.id(), new BigDecimal("998.00"));
Sample output (both pass today; only the second survives a refactor)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -- in com.shoplite.lab.BrittleOrderServiceTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -- in com.shoplite.lab.PlaceOrderOutcomeTest

What this code does

  • The first version describes how placeOrder works, call by call; a cache lookup or a decreaseStock refactor breaks it.
  • The second describes what it achieves: total, stock, stored order, payment and email. It is the version to keep.

An over-mocked test mocks records and values, chains mocks to reach one field, and verifies every call, its count and its order. It passes today and breaks on the next harmless refactor.

The fix is a focused test: real records, fakes for your own repositories, and verify only for effects that leave no state to read, such as a payment or an email. It is shorter and checks more of what matters. Review: Over-mocking (opens in a new tab).

Finish up

Mark complete & continue

Next: Mini project: unit-test the ShopLite order service