Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 119 ยท Testing

Test Doubles and Mockito

Learn the five kinds of test doubles with runnable examples, build a tiny mock library to see how Mockito works, then use when, verify and ArgumentCaptor well.

Real classes rarely work alone. A checkout service charges a card through a payment gateway, saves an order in a database, sends an email and reads the clock. A unit test for that service should not charge a real card, need a running database or depend on what time it is. Instead, you hand the service test doubles: stand-in objects that look like the real dependencies but are fully under the test's control.

In this lesson you will meet the five classic kinds of doubles (dummies, stubs, fakes, spies and mocks), write each one by hand so the ideas are concrete, build a tiny mocking library with java.lang.reflect.Proxy to see how tools like Mockito work inside, and then learn the Mockito API that most Java teams use. Finally, and just as important, you will see when not to mock.

Design for substitution first

A double can only replace a dependency the class does not create itself. Compare:

Java
// Hard to test: the service builds its own dependencies.
class CheckoutService {
    private final StripeGateway gateway = new StripeGateway("sk_live_...");
    private final JdbcOrderRepository orders = new JdbcOrderRepository(Database.connect());
}

// Easy to test: dependencies arrive through the constructor, typed as interfaces.
class CheckoutService {
    private final PaymentGateway gateway;
    private final OrderRepository orders;

    CheckoutService(PaymentGateway gateway, OrderRepository orders) {
        this.gateway = gateway;
        this.orders = orders;
    }
}

The second version uses constructor injection: whoever creates the service decides which implementations it gets. Production code passes the real ones, tests pass doubles. This is the same idea that Spring automates, as you will see in Dependency Injection and Inversion of Control. The same goes for time: take a java.time.Clock instead of calling LocalDateTime.now(), and take a Random or a seed instead of creating one inside.

The five kinds of test doubles

The vocabulary comes from Gerard Meszaros's book xUnit Test Patterns, and it is worth knowing because "mock" is used loosely for all of them:

Double What it does Example
Dummy is passed around but never used a Notifier that is required by the constructor but irrelevant to the test
Stub returns canned answers a gateway that always approves the payment
Fake a working, simplified implementation an in-memory repository backed by a HashMap
Spy a stub that also records how it was called a notifier that stores every message it was asked to send
Mock is preprogrammed with expectations and verifies them "charge must be called exactly once with 2,500 cents"

Stubs and fakes support state verification: you run the code and check the resulting state (the saved order, the returned value). Spies and mocks support behavior verification: you check which calls happened. State verification is usually more robust, because it does not care how the code reached its result.

Here is the service used through the rest of the lesson, tested with a stub, a fake and a dummy, all hand-written:

Java Stubs, fakes and dummies by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice how little code the doubles need when the dependencies are small interfaces: the dummy and the "must not be used" notifier are one-line lambdas, the stub is a record. The fake is the biggest, but it is reusable across every test that touches orders, and it behaves like a real store (ids increase, lookups work), which makes tests read naturally.

Spies: recording what happened

Some behavior has no state to inspect: sending an email, publishing an event, writing an audit log. To test it, record the calls with a spy and assert on the recording. The next example also replaces the system clock with Clock.fixed(...), so the "sent at" timestamp is predictable.

Java A spy and a fixed clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without the fixed clock this test would pass in March 2026 and fail forever after. Any code that reads "now" should get its time from an injected Clock (production passes Clock.systemUTC()), and any code that uses randomness should accept a seeded Random or a Supplier. Dates and times are covered in Dates and Times.

How mocking libraries work: a mock in 40 lines

Writing a class per double gets tedious for interfaces with many methods. Mocking libraries create doubles at runtime. For an interface, the JDK can do it on its own with java.lang.reflect.Proxy: you give it an interface and an InvocationHandler, and every call on the proxy goes to your handler as a Method plus arguments. Record the call, look up a canned answer, return it: that is the core of every mock framework.

The example builds a tiny one. MiniMock.mock(...) creates the proxy, whenCalled(...) stubs an answer, and calls(...) returns the recorded invocations for verification.

Java A tiny mocking library with Proxy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real libraries add three things on top of this: they generate subclasses of classes, not just interfaces (using bytecode tools like Byte Buddy); they match arguments, not just method names; and they offer a fluent, type-safe API so you write when(rates.rate("USD", "GBP")) instead of a method name in a string.

Mockito in practice

Mockito is the most widely used mocking library for Java. It is not on this site's classpath, so the code below is read-only, but it maps directly onto what you just built. Add it next to JUnit (Mockito 5 is current):

XML
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-junit-jupiter</artifactId>
  <version>5.24.0</version> <!-- or the latest 5.x -->
  <scope>test</scope>
</dependency>

mockito-junit-jupiter brings in mockito-core and the JUnit extension. A typical test class:

Java
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.*;

@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {
    @Mock PaymentGateway gateway;
    @Mock OrderRepository orders;
    @Mock Notifier notifier;
    @InjectMocks CheckoutService service;     // built with the three mocks above

    @Captor ArgumentCaptor<String> message;

    @Test
    void approvedPaymentSendsAConfirmation() {
        when(gateway.charge("tok_visa", 2500)).thenReturn(new PaymentResult(true, null));
        when(orders.save(anyString(), eq(2500L), eq(Status.PAID)))
                .thenReturn(new Order(42, "[email protected]", 2500, Status.PAID));

        service.checkout("[email protected]", "tok_visa", 2500);

        verify(gateway, times(1)).charge("tok_visa", 2500);
        verify(notifier).send(eq("[email protected]"), message.capture());
        assertEquals("Order 42 confirmed", message.getValue());
    }

    @Test
    void declinedPaymentNeverTouchesTheDatabase() {
        when(gateway.charge(any(), anyLong())).thenReturn(new PaymentResult(false, "expired"));

        assertThrows(PaymentDeclinedException.class,
                () -> service.checkout("[email protected]", "tok_visa", 2500));

        verifyNoInteractions(orders, notifier);
    }
}

The pieces, mapped to the hand-written versions:

Mockito What it does
mock(Type.class) or @Mock creates a double; unstubbed methods return null, 0, false, empty collections or Optional.empty()
when(mock.call(args)).thenReturn(value) stubs an answer; chain .thenReturn(a, b) for consecutive calls
thenThrow(exception) / thenAnswer(inv -> ...) throws, or computes the answer from the arguments
doThrow(e).when(mock).voidMethod() stubs void methods (they cannot go inside when(...))
verify(mock).call(args) asserts the call happened once; add times(n), never(), atLeastOnce()
verifyNoInteractions(mock) / verifyNoMoreInteractions(mock) asserts nothing (else) was called
ArgumentCaptor / @Captor captures an argument so you can assert on it afterward
any(), anyString(), eq(x), argThat(predicate) argument matchers
spy(realObject) / @Spy wraps a real object: real methods run unless stubbed
@InjectMocks creates the class under test and injects the mocks (constructor first)

Rules that bite newcomers:

  • Matchers are all or nothing. If one argument uses a matcher, every argument must: orders.save(anyString(), eq(2500L), eq(Status.PAID)), not orders.save(anyString(), 2500L, Status.PAID). Mixing them throws InvalidUseOfMatchersException.
  • Strict stubs. With MockitoExtension, a stubbing that the test never uses fails the test with UnnecessaryStubbingException. That is a feature: it removes dead setup. Mark a deliberately shared stub with lenient().
  • Stub with doReturn on spies. when(spy.method()) calls the real method while stubbing; doReturn(x).when(spy).method() does not.
  • Final classes and static methods. Mockito 5 uses the "inline" mock maker by default, which can mock final classes, and try (var mocked = mockStatic(Util.class)) { ... } mocks static methods within a block. Needing either is often a design hint that a dependency should be injected instead.
  • Java 21 and later print a warning when Mockito attaches its agent at runtime, and future JDKs will block that by default. The fix Mockito documents is to load mockito-core as a -javaagent in Surefire's argLine (or Gradle's jvmArgs).

Many teams prefer the BDD aliases in org.mockito.BDDMockito, which read like given/when/then: given(gateway.charge(any(), anyLong())).willReturn(approved) and then(notifier).should().send(...).

When not to mock

Mocks are a sharp tool. Overused, they produce tests that pass while the system is broken, and fail whenever you refactor. Guidelines that experienced teams settle on:

  • Don't mock values. Records, strings, LocalDate, BigDecimal, collections and DTOs are cheap and deterministic. Create real ones.
  • Don't mock the class under test, and don't mock its private helpers. If a part needs isolating, it probably wants to be its own class.
  • Prefer fakes for repositories. An in-memory fake supports any sequence of saves and queries, while a mock has to be told exactly which call returns what, so every refactor of the query logic breaks the test. Better still, test the real repository against a real database in an integration test.
  • Don't mock types you don't own. Mocking HttpClient, ResultSet or a vendor SDK encodes your guess of how it behaves. Wrap the third-party API in a small interface of your own (PaymentGateway), mock that, and test the wrapper with integration tests.
  • Verify outcomes, not implementation. verify(...) is right for side effects that are the behavior (an email was sent, a payment was charged once). Verifying every internal call ties the test to today's implementation.
  • One mock-heavy test is a design smell. If a test needs six mocks, the class has too many responsibilities. Split it.

A useful default: stub queries, verify commands. Calls that return data (findById, rate) get stubbed and are not verified; calls whose purpose is a side effect (send, charge) get verified.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An OrderRepository implementation stores orders in a HashMap and supports save and findById. What kind of test double is it?

    A fake is a working, simplified implementation. It behaves like the real thing for any sequence of calls, unlike a stub that only returns canned answers.
  2. 2. Why does the ReminderService take a Clock in its constructor?

    Injecting the clock makes time a controllable input. Production passes the system clock; tests pass a fixed one, so results never depend on the day the test runs.
  3. 3. What is wrong with when(orders.save(anyString(), 2500L, Status.PAID)) in Mockito?

    Mockito cannot mix raw values and matchers in one call; it throws InvalidUseOfMatchersException. Use eq(2500L) and eq(Status.PAID).
  4. 4. In the tiny Proxy-based library, what happens when the code calls an unstubbed method that returns boolean?

    The handler returns false when no answer is stored for a boolean method, mirroring Mockito, which returns empty defaults (null, 0, false, empty collections) for unstubbed calls.
  5. 5. Which dependency is the best candidate for a mock rather than a real object or a fake?

    Mocks and spies shine for side-effect commands like sending a message. Values should be real, and the class under test must never be mocked.

Summary

  • Make classes testable with constructor injection of interfaces, and inject time (Clock) and randomness too.
  • Dummies fill parameters, stubs return canned answers, fakes are simplified working implementations, spies record calls, mocks verify expected calls.
  • Prefer state verification (stubs, fakes) and keep behavior verification (spies, mocks) for side effects such as emails and payments.
  • Mocking libraries create doubles at runtime; java.lang.reflect.Proxy shows the core idea: intercept the call, record it, return a canned answer.
  • Mockito: @Mock, @InjectMocks, when(...).thenReturn(...), verify(...), ArgumentCaptor, matchers all-or-nothing, strict stubs with MockitoExtension.
  • Don't mock values, the class under test, or types you don't own. Stub queries, verify commands.

Next: Test-Driven Development, where you write the test before the code and let it drive the design.