Over-mocking and brittle tests
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's placeOrder gets a faster stock update. The shop still works, yet ten tests fail. Those tests checked how the code worked, call by call, not what it achieved.
Signs of over-mocking
Over-mocking means replacing more than a test needs, or checking more than the requirement says.
Here is a delivery test with five stubbings to check one date.
Example 1 · Mocks returning mocks: five stubbings for one date
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/main/java/com/shoplite/lab/DeliveryService.java (added to mockito-lab for this lesson)/** Estimates the delivery date from the customer's pincode. */public class DeliveryService {
private final CustomerRepository customers; private final Clock clock;
public DeliveryService(CustomerRepository customers, Clock clock) { this.customers = customers; this.clock = clock; }
public LocalDate estimate(int customerId) { String pincode = customers.findById(customerId).orElseThrow().address().pincode(); int days = pincode.startsWith("56") ? 2 : 5; return LocalDate.now(clock).plusDays(days); }}
// Customer.java and Address.java: two small recordspublic record Customer(int id, String name, Address address) { }public record Address(String city, String pincode) { }
// src/test/java/com/shoplite/lab/DeliveryServiceTest.java (part)@Testvoid estimate_bengaluru_overMocked() { Customer customer = mock(Customer.class); Address address = mock(Address.class); Clock clock = mock(Clock.class); when(customers.findById(1)).thenReturn(Optional.of(customer)); when(customer.address()).thenReturn(address); when(address.pincode()).thenReturn("560038"); when(clock.instant()).thenReturn(Instant.parse("2026-10-16T04:30:00Z")); when(clock.getZone()).thenReturn(INDIA);
LocalDate date = new DeliveryService(customers, clock).estimate(1);
assertEquals(LocalDate.of(2026, 10, 18), date);}[INFO] Running com.shoplite.lab.DeliveryServiceTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.084 s -- in com.shoplite.lab.DeliveryServiceTest
What this code does
customersreturns a mockedCustomer, which returns a mockedAddress, which returns the pincode: a chain of mocks that copies the linefindById(...).orElseThrow().address().pincode().- The
Clockmock needsinstant()andgetZone()because of howLocalDate.nowworks inside the JDK, not because of anythingDeliveryServicesays. - The test passes, which is the danger: it looks fine while costing a change every time the code or the JDK internals change.
Signs of over-mocking:
- Tests break on every refactor, even when the app still works.
- Mocks returning mocks: a mock returns another mock, which returns a third, to reach one value.
- More lines of stubbing than lines of checks, and the stubbing repeats the code under test line by line.
- Every test ends with
verifyNoMoreInteractionsor anInOrderover all mocks.
The delivery test above has five stubbings to check one date. It passes, but each stubbing ties it to one detail of the code: how the pincode is reached, and which Clock methods LocalDate.now happens to call.
Find the bug
Spot the over-mocking
Select the line that is wrong.
Which line is the first sign of over-mocking?
Round 1 of 2Do not mock values, records or types you do not own
A value object holds data and has no dependencies, such as a record Product or Address, a BigDecimal or a LocalDate. Build a real one: a mocked record returns null and 0 for every field you forgot to stub.
Build real values and use a real Clock.fixed. Mock only what the test must replace.
Example 2 · A mocked record, a half-stubbed Clock and String
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/DeliveryServiceTest.java (part)
@Testvoid mockedRecord() { Product product = mock(Product.class); when(product.price()).thenReturn(new BigDecimal("499.00")); System.out.println(product.name() + " costs " + product.price() + ", stock " + product.stock());}
@Testvoid forgotOneClockStub() { Clock clock = mock(Clock.class); when(clock.instant()).thenReturn(Instant.parse("2026-10-16T04:30:00Z")); when(customers.findById(1)) .thenReturn(Optional.of(new Customer(1, "Asha Rao", new Address("Bengaluru", "560038"))));
new DeliveryService(customers, clock).estimate(1);}
@Testvoid mockAString() { String code = mock(String.class);}[INFO] Running com.shoplite.lab.DeliveryServiceTest null costs 499.00, stock 0 [ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 1.106 s <<< FAILURE! -- in com.shoplite.lab.DeliveryServiceTest [ERROR] com.shoplite.lab.DeliveryServiceTest.forgotOneClockStub -- Time elapsed: 0.008 s <<< ERROR! java.lang.NullPointerException: zone ... (frames inside java.util.Objects and java.time.LocalDate) at com.shoplite.lab.DeliveryService.estimate(DeliveryService.java:20) at com.shoplite.lab.DeliveryServiceTest.forgotOneClockStub(DeliveryServiceTest.java:62) [ERROR] com.shoplite.lab.DeliveryServiceTest.mockAString -- Time elapsed: 0.002 s <<< ERROR! org.mockito.exceptions.base.MockitoException: Cannot mock/spy class java.lang.String Mockito cannot mock/spy because : - Cannot mock primitive wrapper types, String, Class, or WeakReference
What this code does
- The mocked
Productprintednullfor the name and0for the stock: no error, just wrong data that a test could silently use. - With only
instant()stubbed,getZone()returnednulland the JDK stopped withNullPointerException: zoneinsideLocalDate.now. - Mockito refuses
String(and wrappers such asInteger): those are values, so use real ones.
Example 3 · The same test with real values and Clock.fixed
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/DeliveryServiceTest.java (part)private static final ZoneId INDIA = ZoneId.of("Asia/Kolkata");
@MockCustomerRepository customers; // the only real dependency to replace
// Simple: real records, a real fixed Clock, one stubbing for the one real dependency@Testvoid estimate_bengaluru() { Clock clock = Clock.fixed(Instant.parse("2026-10-16T04:30:00Z"), INDIA); when(customers.findById(1)) .thenReturn(Optional.of(new Customer(1, "Asha Rao", new Address("Bengaluru", "560038"))));
LocalDate date = new DeliveryService(customers, clock).estimate(1);
assertEquals(LocalDate.of(2026, 10, 18), date);}[INFO] Running com.shoplite.lab.DeliveryServiceTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.902 s -- in com.shoplite.lab.DeliveryServiceTest
What this code does
- Real
CustomerandAddressrecords replace two mocks, andClock.fixed(10:00 India time on 16 October 2026) replaces the third. - One stubbing remains, for the one real dependency the test must replace: the repository.
A type you do not own comes from the JDK or a library: Clock, HttpClient, List. Mocking it means guessing how its other code calls it. LocalDate.now(clock) calls both instant() and getZone(); stub one and you get NullPointerException: zone. Use the real thing when it is easy (Clock.fixed, new ArrayList<>()), or wrap the library behind an interface you own and mock that.
Mockito also refuses some JDK types outright: String, primitive wrappers such as Integer, and Class cannot be mocked.
Predict the output
Mocking a type you do not own
Read the code and pick what it prints.
What does this program do?
Verifying implementation details instead of outcomes
An implementation detail is how the code reaches its result: which repository method it calls, how often, in which order. An outcome is the result itself: the total, the stock left, the order stored.
The same two tests run against two versions of a service: one test checks calls, the other checks results.
Example 4 · A refactor breaks the call-checking test, not the outcome test
import java.math.BigDecimal;import java.util.ArrayList;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);
void updateStock(int productId, int newStock);
void decreaseStock(int productId, int quantity); // added later: one atomic UPDATE in SQL}
interface OrderRepository { int save(int productId, int quantity, BigDecimal total);}
interface OrderService { int placeOrder(int productId, int quantity);}
/** Version 1: reads the stock, works out the new value, writes it back. */class OrderServiceV1 implements OrderService { private final ProductRepository products; private final OrderRepository orders;
OrderServiceV1(ProductRepository products, OrderRepository orders) { this.products = products; this.orders = orders; }
public int placeOrder(int productId, int quantity) { Product p = products.findById(productId).orElseThrow(); products.updateStock(productId, p.stock() - quantity); return orders.save(productId, quantity, p.price().multiply(BigDecimal.valueOf(quantity))); }}
/** Version 2 (refactored): same behaviour, but uses decreaseStock. */class OrderServiceV2 implements OrderService { private final ProductRepository products; private final OrderRepository orders;
OrderServiceV2(ProductRepository products, OrderRepository orders) { this.products = products; this.orders = orders; }
public int placeOrder(int productId, int quantity) { Product p = products.findById(productId).orElseThrow(); products.decreaseStock(productId, quantity); return orders.save(productId, quantity, p.price().multiply(BigDecimal.valueOf(quantity))); }}
/** A fake that also records every call, so both kinds of test can use it. */class RecordingFakeRepos implements ProductRepository, OrderRepository { final List<String> calls = new ArrayList<>(); final Map<Integer, Product> products = new HashMap<>(); final List<String> savedOrders = new ArrayList<>();
RecordingFakeRepos() { products.put(9, new Product(9, "Clean Code", new BigDecimal("499.00"), 30)); }
public Optional<Product> findById(int id) { calls.add("findById(" + id + ")"); return Optional.ofNullable(products.get(id)); }
public void updateStock(int productId, int newStock) { calls.add("updateStock(" + productId + ", " + newStock + ")"); Product p = products.get(productId); products.put(productId, new Product(p.id(), p.name(), p.price(), newStock)); }
public void decreaseStock(int productId, int quantity) { calls.add("decreaseStock(" + productId + ", " + quantity + ")"); Product p = products.get(productId); products.put(productId, new Product(p.id(), p.name(), p.price(), p.stock() - quantity)); }
public int save(int productId, int quantity, BigDecimal total) { calls.add("save(" + productId + ", " + quantity + ", " + total + ")"); savedOrders.add(quantity + " x product " + productId + " = " + total); return 16 + savedOrders.size(); }}
public class BrittleVsSturdyDemo {
/** Brittle: demands the exact list of calls, so it describes HOW the code works. */ static String brittleTest(RecordingFakeRepos repos, OrderService service) { service.placeOrder(9, 2); List<String> expected = List.of("findById(9)", "updateStock(9, 28)", "save(9, 2, 998.00)"); return repos.calls.equals(expected) ? "PASS" : "FAIL, calls were " + repos.calls; }
/** Sturdy: checks the outcome, so it describes WHAT the code achieves. */ static String sturdyTest(RecordingFakeRepos repos, OrderService service) { int orderId = service.placeOrder(9, 2); boolean ok = orderId == 17 && repos.products.get(9).stock() == 28 && repos.savedOrders.equals(List.of("2 x product 9 = 998.00")); return ok ? "PASS" : "FAIL"; }
public static void main(String[] args) { RecordingFakeRepos a = new RecordingFakeRepos(); RecordingFakeRepos b = new RecordingFakeRepos(); System.out.println("Version 1:"); System.out.println(" brittle test: " + brittleTest(a, new OrderServiceV1(a, a))); System.out.println(" sturdy test: " + sturdyTest(b, new OrderServiceV1(b, b)));
RecordingFakeRepos c = new RecordingFakeRepos(); RecordingFakeRepos d = new RecordingFakeRepos(); System.out.println("Version 2 (refactored, same behaviour):"); System.out.println(" brittle test: " + brittleTest(c, new OrderServiceV2(c, c))); System.out.println(" sturdy test: " + sturdyTest(d, new OrderServiceV2(d, d))); }}Version 1: brittle test: PASS sturdy test: PASS Version 2 (refactored, same behaviour): brittle test: FAIL, calls were [findById(9), decreaseStock(9, 2), save(9, 2, 998.00)] sturdy test: PASS
What this code does
- Both versions take 2 units of product 9, reduce its stock from 30 to 28 and save an order of 998.00; only the repository method used differs.
- The brittle test compares the exact list of calls, so version 2 fails it with
decreaseStock(9, 2)in the list. - The sturdy test checks the order id, the stock and the saved order, and passes for both versions.
Tests that verify details break when the code is improved. Changing updateStock(9, 28) into an atomic decreaseStock(9, 2) is a good refactor: one SQL UPDATE instead of read-then-write. Yet a test that demands the old call fails, although the stock is still 28.
Verify a call only when the call is the outcome: money charged, a message sent, nothing saved on an error path. The example runs the same two tests against two versions of a service.
Rewriting a brittle test to check results
A brittle test breaks after a change that kept the behaviour correct, usually because it copies how the code works, call by call, instead of checking what it achieves.
Rewrite a brittle test in three steps. The example shows the same test before and after.
Example 5 · Before and after: rewriting the placeOrder test
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// BEFORE: src/test/java/com/shoplite/lab/BrittleOrderServiceTest.javaimport java.math.BigDecimal;import java.util.Optional;
import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.InOrder;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;
/** Before: every call, its count and its order. Passes today, breaks on the next refactor. */@ExtendWith(MockitoExtension.class)class BrittleOrderServiceTest {
@Mock ProductRepository products; @Mock OrderRepository orders; @Mock PaymentGateway payments; @Mock EmailSender emails;
@InjectMocks OrderService service;
@Test void placeOrder_works() { 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"));
service.placeOrder(1, 9, 2);
InOrder inOrder = inOrder(products, payments, orders, emails); inOrder.verify(products, times(1)).findById(9); inOrder.verify(payments).charge(1, new BigDecimal("998.00")); inOrder.verify(products).updateStock(9, 28); inOrder.verify(orders).save(any(Order.class)); inOrder.verify(emails).sendOrderConfirmation(1, 17, new BigDecimal("998.00")); verifyNoMoreInteractions(products, payments, orders, emails); }}
// AFTER: src/test/java/com/shoplite/lab/PlaceOrderOutcomeTest.javaimport java.math.BigDecimal;import java.util.List;
import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;
/** After: the outcome. Fakes for our repositories, mocks only where the call is the result. */@ExtendWith(MockitoExtension.class)class PlaceOrderOutcomeTest {
InMemoryProductRepository products = new InMemoryProductRepository(new Product(9, "Clean Code", new BigDecimal("499.00"), 30)); InMemoryOrderRepository orders = new InMemoryOrderRepository(); @Mock PaymentGateway payments; @Mock EmailSender emails;
OrderService service;
@BeforeEach void setUp() { service = new OrderService(products, orders, payments, emails); }
@Test void placeOrder_chargesTheTotalStoresTheOrderAndReducesStock() { when(payments.charge(eq(1), any(BigDecimal.class))).thenReturn("pay_501");
Order order = service.placeOrder(1, 9, 2);
assertEquals(new BigDecimal("998.00"), order.total()); assertEquals(28, products.findById(9).orElseThrow().stock()); assertEquals(List.of(order), orders.findByCustomer(1)); verify(payments).charge(1, new BigDecimal("998.00")); // money: the call is the result verify(emails).sendOrderConfirmation(1, order.id(), new BigDecimal("998.00")); }}[INFO] Running com.shoplite.lab.BrittleOrderServiceTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.941 s -- in com.shoplite.lab.BrittleOrderServiceTest [INFO] Running com.shoplite.lab.PlaceOrderOutcomeTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.012 s -- in com.shoplite.lab.PlaceOrderOutcomeTest
What this code does
- Before: three stubbings, an
InOrderover four mocks,times(1)on a lookup andverifyNoMoreInteractions. Any new call or reordering breaks it. - After: fakes for the two repositories, so the test reads the stock (28) and the stored order back;
verifyremains only for the payment and the email. - Both pass today. Only the second still passes after the
decreaseStockrefactor or an added cache lookup.
The steps:
- Write down what the test should prove, in business words: "the customer is charged the total, the order is stored with that total, the stock drops by the quantity, and a confirmation is sent".
- Replace mocks of your own simple types with fakes, so the results can be read back.
- Keep
verifyonly for effects that leave no state to read (payment, email), and dropInOrder,times(1)on lookups andverifyNoMoreInteractionsunless a rule needs them.
The rewritten test is shorter, checks more of what matters, and survives the decreaseStock refactor because the fake supports both ways of reducing stock.
Order of execution
Order the steps of a rewrite
Tap the steps in the order they happen.
save.Next step
Check your understanding
12 quick questions