Mockito in Depth: Faking Collaborators

Mockito in Depth: Faking Collaborators in Java: Unit tests must be fast and deterministic. A service that talks to a database, a payment API, and the system…

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

  1. Mocking everything: A test where every collaborator is stubbed verifies your stubs, not your code.
  2. Over-verification: Asserting on every interaction makes the test break on harmless refactors.
  3. Unnecessary stubbing: MockitoExtension fails the test for unused stubs — that is a feature, delete them.
  4. when() on a void method: Use doThrow(...).when(mock).method() instead.
  5. Mocking the class under test: Then you are testing nothing at all.

Best Practices

  • Inject dependencies through the constructor — it is what makes @InjectMocks work cleanly.
  • Verify behaviour, not implementation: Check that payment was charged, not the order of six internal calls.
  • Inject a Clock rather than calling LocalDateTime.now(), so time is testable.
  • Prefer real objects for simple values: Mocking a Money class is pure overhead.

Practice Exercises

  1. The Captor: Use ArgumentCaptor to assert on an object your service built and passed to a repository.
  2. The Timeout Path: Stub a client to throw, and verify your service records a failure state.
  3. The Strict Stub: Add a stub your code never uses and watch MockitoExtension fail the test. Explain why that is helpful.