Lesson 3 of 5 · 11 min · Unit testing in Java

Mocks and stubs with Mockito

Covers: JUnit 6 with Mockito 5 and AssertJ on Java 17 or newer. Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • Why unit tests replace dependencies with test doubles
  • The difference between a dummy, stub, mock, spy and fake
  • Use Mockito: @Mock, @InjectMocks, when, verify, ArgumentCaptor
  • Simulate failures and verify interactions
  • Avoid over-mocking, and know when a fake is better

In simple words

Suppose you are testing the checkout code. It needs a payment gateway that charges real money, an email service that sends real emails and a database. You do not want your test to do any of that. So you swap each of them for a stand-in that you control: one that says "payment accepted" when you want, or "payment failed", and that remembers what it was asked to do. Your test then checks the checkout logic in a safe, fast and predictable setting.

Words to know

  • Test double: a stand-in object used in place of a real dependency in a test.
  • Stub: a double that returns prepared answers.
  • Mock: a double that also records calls so the test can check them.
  • Fake: a simple working implementation, such as an in-memory repository.

Test doubles

Double What it does Example
Dummy passed only to fill a parameter, never used null or an empty object
Stub returns canned answers to calls repo.findById(1) returns this order
Mock stub plus records calls; the test verifies them verify that emailSender.send(...) was called once
Spy wraps a real object, records calls, can override a few methods partial mocking
Fake a lightweight working implementation an InMemoryOrderRepository backed by a HashMap

Many people say "mock" for all of them; Mockito creates objects that can act as stubs or mocks.

The code under test

public class CheckoutService {
    private final OrderRepository orders;
    private final PaymentGateway payments;
    private final EmailSender email;

    public CheckoutService(OrderRepository orders, PaymentGateway payments, EmailSender email) {
        this.orders = orders;
        this.payments = payments;
        this.email = email;
    }

    public Receipt checkout(long orderId) {
        Order order = orders.findById(orderId).orElseThrow(() -> new OrderNotFoundException(orderId));
        PaymentResult result = payments.charge(order.customerId(), order.amount());
        if (!result.success()) {
            throw new PaymentFailedException("payment declined for order " + orderId);
        }
        order.markPaid();
        orders.save(order);
        email.sendReceipt(order.customerEmail(), order.id());
        return new Receipt(order.id(), order.amount());
    }
}

Because the dependencies come in through the constructor (the SOLID lesson), a unit test can pass doubles.

Mockito basics

Mockito is the most popular mocking library; Spring Boot's test starter includes it. Use the JUnit extension:

@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {

    @Mock OrderRepository orders;
    @Mock PaymentGateway payments;
    @Mock EmailSender email;
    @InjectMocks CheckoutService service;           // built with the mocks above

    @Test
    void successfulCheckoutMarksPaidSavesAndEmails() {
        Order order = new Order(7L, 3L, new BigDecimal("1200"), "asha@example.com");
        when(orders.findById(7L)).thenReturn(Optional.of(order));                 // stub
        when(payments.charge(3L, new BigDecimal("1200"))).thenReturn(PaymentResult.ok());

        Receipt receipt = service.checkout(7L);

        assertThat(receipt.orderId()).isEqualTo(7L);
        assertThat(order.status()).isEqualTo(OrderStatus.PAID);
        verify(orders).save(order);                                               // verify the interaction
        verify(email).sendReceipt("asha@example.com", 7L);
    }
}

Key tools:

  • @Mock creates a mock; @InjectMocks creates the object under test and injects the mocks into its constructor (or you can write new CheckoutService(orders, payments, email) yourself, which is often clearer).
  • when(call).thenReturn(value) stubs a return value; thenThrow(new X()) makes it fail; thenReturn(a, b, c) returns values in turn; thenAnswer(inv -> ...) computes the answer.
  • For void methods use doThrow(new X()).when(mock).method(args) and doNothing().
  • verify(mock).method(args) checks it was called once with those arguments; verify(mock, times(2)), never(), atLeastOnce(), verifyNoInteractions(mock), verifyNoMoreInteractions(mock), and InOrder for ordering.
  • Argument matchers: any(), anyLong(), eq(x), argThat(...). If you use a matcher for one argument you must use matchers for all arguments of that call (wrap plain values with eq).
  • Unstubbed methods return defaults: null, 0, false, empty collections, and Optional.empty().

Simulating failures

@Test
void declinedPaymentDoesNotSaveOrSendEmail() {
    Order order = new Order(7L, 3L, new BigDecimal("1200"), "asha@example.com");
    when(orders.findById(7L)).thenReturn(Optional.of(order));
    when(payments.charge(anyLong(), any())).thenReturn(PaymentResult.declined());

    assertThatThrownBy(() -> service.checkout(7L))
            .isInstanceOf(PaymentFailedException.class);

    verify(orders, never()).save(any());
    verifyNoInteractions(email);
}

@Test
void unknownOrderThrowsNotFound() {
    when(orders.findById(99L)).thenReturn(Optional.empty());

    assertThatThrownBy(() -> service.checkout(99L)).isInstanceOf(OrderNotFoundException.class);
    verifyNoInteractions(payments);
}

@Test
void gatewayTimeoutIsPropagated() {
    when(orders.findById(7L)).thenReturn(Optional.of(order()));
    when(payments.charge(anyLong(), any())).thenThrow(new GatewayTimeoutException());

    assertThatThrownBy(() -> service.checkout(7L)).isInstanceOf(GatewayTimeoutException.class);
}

Failure paths are where mocks shine: it is hard to make a real gateway time out on demand, trivial with a mock.

Capturing arguments

When the object passed to a collaborator is built inside the method, capture it and inspect it:

@Captor ArgumentCaptor<AuditEvent> eventCaptor;

@Test
void checkoutWritesAuditEvent() {
    // ... arrange and act ...
    verify(audit).record(eventCaptor.capture());
    assertThat(eventCaptor.getValue().type()).isEqualTo("ORDER_PAID");
    assertThat(eventCaptor.getValue().orderId()).isEqualTo(7L);
}

Strict stubs

With MockitoExtension, Mockito runs in strict mode: it fails the test if you stub something that is never used (UnnecessaryStubbingException) or call a stubbed method with different arguments than expected (PotentialStubbingProblem). That is a feature: it removes dead setup and catches typos. Stub only what the test needs.

Spies

A spy wraps a real object so you can stub part of it:

List<String> real = new ArrayList<>();
List<String> spy = spy(real);
doReturn(100).when(spy).size();           // use doReturn for spies (the real method is not called)

Use spies rarely; a need for a spy often signals that a class does too much.

Mocking rules of thumb

  • Mock your own boundaries (repositories, gateways, clients) when testing the class that uses them.
  • Do not mock value objects, simple data classes, collections or things you can create for real (List, BigDecimal, records), and do not mock the class under test.
  • Do not mock types you do not own deeply (a JDBC Connection, a Spring RestTemplate chain); wrap them in your own interface, and test that wrapper with an integration test.
  • Verify behaviour that matters (an email was sent, nothing was saved on failure), not every call. Over-verification locks tests to the implementation and breaks on every refactor.
  • Prefer a fake (in-memory repository) when the test needs realistic behaviour across several calls (save then find). Fakes are less brittle than long when chains.
  • If you need ten mocks to test a class, the class has too many dependencies; split it.

Mockito with Spring Boot

For plain unit tests, use MockitoExtension as above, with no Spring context (fast). In Spring tests that load a context (@WebMvcTest, @SpringBootTest), replace a bean with a mock using @MockitoBean (Spring Framework 6.2 and later; Spring Boot 4 removed @MockBean), covered in the Spring testing lesson. Spring's mocks start the framework, which is much slower than a plain unit test, so use them only where you need the web or persistence layer.

Common mistakes

  • Over-mocking: testing the mocks instead of the code.
  • Verifying every interaction, making tests brittle.
  • Mixing matchers and raw values in one call.
  • Stubbing with when(spy.method()) (calls the real method), instead of doReturn.
  • Mocking the class under test or simple value objects.
  • Unnecessary stubs that strict mode will flag.
  • Leaving out a failure-path test because "mocking is hard".

Try it yourself

  1. Write CheckoutService and the three tests above with Mockito, running with MockitoExtension.
  2. Add a test that captures the argument passed to the audit collaborator.
  3. Break the code so it emails even when payment fails, and see which test catches it.
  4. Replace the mocked OrderRepository with an in-memory fake and compare the tests' readability.
  5. Cause an UnnecessaryStubbingException on purpose and read the message.

Check yourself

What is the difference between a stub and a mock?

A stub just returns prepared answers; a mock also records calls so a test can verify that they happened.

What does verify(email, never()).sendReceipt(any(), anyLong()) check?

That sendReceipt was never called, for example because a payment failed.

Why does Mockito's strict mode fail on unused stubs?

Unused stubs are dead setup or signs of a typo; failing them keeps tests focused on what the code really uses.

When is a fake better than a mock?

When the test needs realistic behaviour across several calls, like saving and then finding, where long when chains would be fragile.

Interview questions

What is the difference between a mock and a spy in Mockito?

A mock is a completely fake object whose methods do nothing or return defaults unless stubbed. A spy wraps a real object and calls the real methods unless you stub specific ones.

How do you test a method that returns void?

Check its effects: verify interactions with collaborators (verify), capture arguments, or assert on state changes of the object or arguments; for exceptions use doThrow and assertThrows.

What are the dangers of over-mocking?

Tests become coupled to implementation details, break on harmless refactors, pass while real integrations are broken, and verify the mocks rather than behaviour.

Summary

  • Test doubles (dummy, stub, mock, spy, fake) replace slow or unpredictable dependencies.
  • With Mockito: @Mock, when/thenReturn, thenThrow, verify, ArgumentCaptor; MockitoExtension gives strict stubs.
  • Mock your own boundaries and failure paths; verify behaviour that matters, not every call.
  • Prefer fakes for stateful collaborators; too many mocks means too many responsibilities.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Unit testing in Java with JUnit and Mockito for Java Full Stack Developer and scores every answer, with what to fix.