Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Patterns and Pitfalls

Fakes, Stubs and Mocks: Choosing

Compare dummies, stubs, fakes, spies and mocks with runnable Java, learn when an in-memory fake beats a Mockito mock, and get a checklist for picking the right double.

People say "mock" for every kind of test double, but the kinds behave differently and suit different jobs. Choosing well makes tests shorter, sturdier and easier to read. In this lesson you will compare the five kinds side by side, write an in-memory fake that often beats a Mockito mock, and finish with a checklist.

The runnable code is plain Java plus the labelled Mini stand-in. Mockito is not available here, so real Mockito lines are read-only.

The vocabulary

Double What it does Typical Mockito form
Dummy Fills a parameter and is never used mock(Foo.class) passed and ignored
Stub Returns canned answers to calls when(x.get()).thenReturn(...)
Fake A working, simplified implementation (in-memory repo) Hand-written class
Spy Real object that records calls spy(obj)
Mock Pre-programmed with expectations, verifies calls mock(Foo.class) + verify(...)

In daily Mockito use the first, second and fifth are all mock(...). What differs is how you use it: a stub supplies data (no verify), a mock is verified.

flowchart LR
  I["Input side: data coming in"] --> S["Stub / Fake"]
  O["Output side: effects going out"] --> M["Mock / Spy + verify"]

Stub what the code reads; verify what the code does to the outside world.

Stubs: feed data in

Use a stub when the class needs an answer from a collaborator and you want to control it. Never verify a stub: the answer you got back proves the call happened.

Java
when(rates.vat("DE")).thenReturn(0.19);
assertEquals(119.0, service.gross("DE", 100.0), 0.001);   // no verify(rates...) needed

Mocks: check effects out

Use a mock when the call itself is the result: an email, a payment request, a published event.

Java
service.cancel(orderId);
verify(mailer).send(eq("[email protected]"), contains("cancelled"));

Fakes: a small working copy

A fake is a lightweight real implementation, such as an in-memory repository, a map-backed cache or a clock you can move. Unlike a mock it has behavior: save then find returns what you saved. Tests become stories instead of scripts.

Compare the same test with a mock repo and with a fake repo.

Java Mock script versus in-memory fake

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.

The mock version needs a stub for find and checks one interaction. The fake version tests a whole scenario (create, then duplicate) with no stubbing at all, and the final state is what you assert on. Add a delete method later and the fake test keeps working unchanged.

When a fake wins

  • The collaborator has state and several related methods (repositories, caches, queues).
  • Many tests use it: write the fake once, reuse it everywhere.
  • You want tests that survive refactoring of how the code talks to the collaborator.

When a mock wins

  • The collaborator is an outgoing channel with no state to simulate (mailer, notifier, audit log).
  • You need to simulate failures on demand: doThrow(new IOException()).when(mailer).send(...).
  • Writing a fake would cost more than the tests are worth.

You can also combine them: a fake repository for state, a Mockito mock for the mailer.

Java Fake repository plus a mock for the outgoing email

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.

State lives in the fake, the one effect that leaves the system is verified on the mock.

Contract tests keep fakes honest

A fake can drift from the real implementation. The remedy is a contract test: one test class run against both the fake and the real repository (against a test database), asserting the same behavior, such as "save then find returns the user" and "find of an unknown id is empty". Then you can trust the fake in all other tests.

A checklist

  1. Does the code read from it? Stub or fake. Does it write to the outside? Mock and verify.
  2. Does it hold state across calls? Prefer a fake.
  3. Is it a value or pure logic? Use the real thing.
  4. Will this test still pass if I restructure the internals? If not, you are probably over-specifying with mocks.
  5. Do I need the real object mostly? Spy, with care (Spies basics).

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which double has real, simplified behavior such as an in-memory repository?

    A fake is a working lightweight implementation. Save followed by find returns what was saved.
  2. 2. When should you verify a call on a Mockito mock?

    Verify effects that leave the system. Data you stubbed need not be verified because using the result proves it.
  3. 3. What is a contract test for a fake?

    Running the same tests on both implementations keeps the fake honest.

Summary

  • Dummies fill parameters, stubs supply data, fakes simulate behavior, spies wrap real objects, mocks verify effects.
  • Stub inputs; verify outputs; do not verify stubs.
  • Prefer fakes for stateful collaborators like repositories; prefer mocks for outgoing effects and failure injection.
  • Contract tests keep fakes aligned with real implementations.

Next: Troubleshooting common Mockito errors