Concept Explanation
Unit tests must be fast and deterministic. A service that talks to a database, a payment API, and the system clock is none of those things. Mocks replace those collaborators with objects you fully control.
Rule of thumb: mock things you do not own or cannot control — repositories, HTTP clients, clocks, message publishers. Do not mock value objects or the class under test.
The Standard Setup
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock PaymentGateway gateway;
@Mock OrderRepository repo;
@InjectMocks OrderService service; // mocks injected via constructor
@Test
void chargesAndSavesOnSuccess() {
// Arrange
when(gateway.charge(anyLong(), any())).thenReturn(PaymentResult.ok("txn-1"));
when(repo.save(any(Order.class))).thenAnswer(i -> i.getArgument(0));
// Act
Order result = service.place(42L, BigDecimal.TEN);
// Assert
assertEquals("txn-1", result.getTransactionId());
verify(gateway).charge(42L, BigDecimal.TEN);
verify(repo).save(any(Order.class));
}
}
Stubbing Patterns
when(repo.findById(1L)).thenReturn(Optional.of(user)); // fixed value
when(repo.findById(9L)).thenReturn(Optional.empty()); // absent
when(gateway.charge(any(), any()))
.thenThrow(new GatewayTimeoutException()); // failure path
when(clock.now()).thenReturn(FIXED_INSTANT); // frozen time
// Different result on each successive call
when(feed.next()).thenReturn("a", "b", "c");
// Void methods use a different form
doThrow(new IllegalStateException()).when(publisher).publish(any());
Verification
verify(repo).save(order); // exactly once (default)
verify(email, times(2)).send(any());
verify(email, never()).send(argThat(m -> m.getTo() == null));
verify(gateway, atLeastOnce()).charge(any(), any());
verifyNoMoreInteractions(repo);
// Inspect exactly what was passed
ArgumentCaptor<Order> captor = ArgumentCaptor.forClass(Order.class);
verify(repo).save(captor.capture());
assertEquals(OrderStatus.PAID, captor.getValue().getStatus());
ArgumentCaptor is the tool for asserting on objects your code constructed internally.
Testing the Failure Path
This is where mocks earn their keep — you cannot easily make a real gateway time out on demand:
@Test
void marksOrderFailedWhenGatewayTimesOut() {
when(gateway.charge(any(), any())).thenThrow(new GatewayTimeoutException());
assertThrows(OrderFailedException.class,
() -> service.place(42L, BigDecimal.TEN));
verify(repo).save(argThat(o -> o.getStatus() == OrderStatus.FAILED));
}
Common Mistakes
- Mocking everything: A test where every collaborator is stubbed verifies your stubs, not your code.
- Over-verification: Asserting on every interaction makes the test break on harmless refactors.
- Unnecessary stubbing:
MockitoExtensionfails the test for unused stubs — that is a feature, delete them. when()on a void method: UsedoThrow(...).when(mock).method()instead.- Mocking the class under test: Then you are testing nothing at all.
Best Practices
- Inject dependencies through the constructor — it is what makes
@InjectMockswork cleanly. - Verify behaviour, not implementation: Check that payment was charged, not the order of six internal calls.
- Inject a
Clockrather than callingLocalDateTime.now(), so time is testable. - Prefer real objects for simple values: Mocking a
Moneyclass is pure overhead.
Practice Exercises
- The Captor: Use
ArgumentCaptorto assert on an object your service built and passed to a repository. - The Timeout Path: Stub a client to throw, and verify your service records a failure state.
- The Strict Stub: Add a stub your code never uses and watch
MockitoExtensionfail the test. Explain why that is helpful.