Skip to content
javahacks.dev
Testing

Test Doubles Mocks Stubs Fakes and Spies Explained

Tell dummies, stubs, spies, mocks and fakes apart with a Java example of each, and learn which one to reach for in a given test.

6 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the Selenium and Jenkins logos.

Developers use the word mock for any object that stands in for a real one in a test, and the looseness costs them. The terms were separated by Gerard Meszaros into five kinds of test double, and the differences have practical consequences: tests that verify too much break when code is refactored, and tests that use the wrong kind of double pass while the production code is broken. This post defines the five, shows each in Java with Mockito where it applies, and gives a rule for choosing. The vocabulary is general, and the examples use JUnit 5 and Mockito 5.

Dummy: fills a slot

A dummy is passed to satisfy a parameter and is never used. It exists because a constructor demands an argument the test does not care about.

java
var service = new InvoiceService(new FakeRepository(), null);   // the mailer is never touched in this test

Sometimes it is null, sometimes a mock with no behaviour. If a dummy is used, the test will fail with an exception, which is useful. The need for many dummies is a sign that the class has too many collaborators, a design smell discussed in constructor injection.

Stub: returns canned answers

A stub provides fixed responses so the code under test can proceed along the path the test needs. It is about inputs.

java
TaxRates rates = mock(TaxRates.class);
when(rates.rateFor("DE")).thenReturn(new BigDecimal("0.19"));

var calculator = new PriceCalculator(rates);
assertEquals(new BigDecimal("119.00"), calculator.gross(new BigDecimal("100.00"), "DE"));

The test asserts on the result of the code, and the stub only makes the scenario possible. Nothing checks that rateFor was called, because the result already depends on it. For an interface with a single method, a lambda is a stub with no library: country -> new BigDecimal("0.19").

Spy: records what happened

A spy wraps a real or fake object and records the calls made on it, so the test can look at them afterwards.

java
var mailer = spy(new RecordingMailer());
service.sendReminders(overdueInvoices);

assertEquals(3, mailer.sent().size());

The point is to observe an effect that has no return value. Spies are the double behind many checks of "was it called", and Mockito's spy applies to real objects; its use and hazards are in Mockito spies.

Mock: expects interactions

A mock is pre-programmed with expectations about the calls it should receive, and the test fails if they do not happen. It is about outputs, the side effects of the code under test.

java
var gateway = mock(PaymentGateway.class);
service.checkout(cart);

verify(gateway).charge(eq(cart.total()), any());
verifyNoMoreInteractions(gateway);

A mock is the right choice when the interaction is the behaviour: sending an email, publishing an event, charging a card. There is no return value or state to inspect; the call is the requirement. The key distinction in Fowler's article Mocks Aren't Stubs is between state verification, checking the result, and behaviour verification, checking the calls. Mockito objects are used for both roles, which is the origin of the confusion.

Fake: a working shortcut

A fake is a real implementation that is simpler than production: an in-memory repository, a fake clock, a local file system in place of cloud storage.

java
class InMemoryOrderRepository implements OrderRepository {

    private final Map<Long, Order> store = new HashMap<>();

    @Override public Order save(Order order) { store.put(order.id(), order); return order; }
    @Override public Optional<Order> find(long id) { return Optional.ofNullable(store.get(id)); }
}

A fake behaves the way the real thing does, so tests of the service using it check outcomes: save an order, find it, and see it. There are no expectations to set up and no stubbing to repeat in a hundred tests. A fake costs effort to write once and pays back across many tests. It also needs to be right, so give it its own tests, ideally the same contract test that the real implementation passes.

Which to pick

You want toUse
Satisfy a parameter that is not usedDummy
Give the code a specific input from a dependencyStub
Verify an effect that has no return valueMock or spy
Run realistic scenarios across many testsFake
Check behaviour with a real database or brokerNeither; use a real one in a container

Prefer fakes and stubs and check state. Reserve mocks for interactions that are the requirement. This order produces tests that survive refactoring, as the guidance in mocks versus real objects argues, and it fits the proportions of a practical test strategy.

The cost of verifying everything

The failure of overusing mocks is tests that restate the implementation. A test that verifies every call the code makes to its collaborators, in order, breaks when the code is restructured without any change in behaviour, such as batching two calls into one. The test then protects the structure and not the behaviour, which is the opposite of its job. Verify only the interactions that are observable requirements. Mockito helps here: verifyNoMoreInteractions makes a test stricter, and strict stubs report unused stubbing as an error, as explained in UnnecessaryStubbingException. Both are tools to use on purpose, not by default.

Contract tests keep fakes honest

A fake is only useful while it behaves like the real thing. Write one test class against the interface and run it against both implementations:

java
abstract class OrderRepositoryContract {
    abstract OrderRepository create();

    @Test void findsWhatWasSaved() {
        var repo = create();
        repo.save(new Order(1L, "OPEN"));
        assertEquals("OPEN", repo.find(1L).orElseThrow().status());
    }

    @Test void unknownIdIsEmpty() {
        assertTrue(create().find(99L).isEmpty());
    }
}

class InMemoryOrderRepositoryTest extends OrderRepositoryContract {
    OrderRepository create() { return new InMemoryOrderRepository(); }
}

class JpaOrderRepositoryIT extends OrderRepositoryContract {
    OrderRepository create() { return realRepositoryOnTestcontainersDatabase(); }
}

When the real repository changes behaviour, say it starts rejecting duplicates, the contract fails against the fake until you update it. That keeps the thousand tests that use the fake truthful. Without this step, fakes drift and tests pass against a world that no longer exists.

A worked comparison

Take a service that sends a reminder email for each overdue invoice. A test built on a mock says: verify(mailer, times(3)).send(any()). It fails if the service batches the three emails into one call, even though the customers get the right messages. A test built on a recording fake says: the fake mailer holds three messages, addressed to the right customers, containing the right invoice numbers. It passes if the service batches or not, and it fails only when the outcome is wrong. The second test is longer to set up once and survives every internal refactoring.

Use the mock when the call is the requirement and nothing else can show it happened, for example a call to an audit service that has no observable state in the test. Use the fake whenever the effect can be read back. The habit to build is asking, for each double, what outcome the test cares about, and choosing the cheapest double that can show it. Over time, the suite holds fewer mocks, runs just as fast, and breaks less during refactoring, which is the measure of whether a test suite is helping.

Where the vocabulary does not help

Teams argue about whether a particular object is a stub or a mock. The argument is not the point. Ask what the double is for: to supply input, to observe output, or to stand in for a working system. The tooling is documented in the Mockito Javadoc, and the taxonomy comes from Meszaros's book *xUnit Test Patterns*.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.