Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

When would you prefer a fake (for example an in-memory repository) over Mockito mocks in service tests?

I prefer a fake when many tests need the same consistent behaviour from a collaborator, such as a repository where what we save must be found again: one in-memory implementation replaces dozens of repeated stubs, and because tests then check resulting state instead of calls, they survive refactoring. The price is that the fake must be maintained and must behave like the real thing, which a shared contract test run against both proves. Mocks remain the better tool for verifying calls to side-effecting collaborators, such as an email sender.

Why this question is asked

Most Java teams reach for Mockito by default, and for good reason: it is quick and it works for any interface. But in service tests with a repository at their centre, a suite built entirely on mocks tends to become a wall of when(...).thenReturn(...) lines that break whenever the service changes how it queries. Interviewers ask this design question to see whether we can choose the right double for the job and explain the trade-off. In this answer, we will see the problem with repeated stubs, rewrite the tests with a fake, look at why state-based tests survive refactoring, keep the fake honest with a contract test, and decide where mocks still win.

1The Problem With Repeated Stubs

Consider an order service with a repository. Every test that touches orders must stub the repository for the exact calls the service makes. Here are two of many such tests.

Java
@Test void cancelsOpenOrder() {
Order order = new Order(42L, OPEN);
when(repo.findById(42L)).thenReturn(Optional.of(order));
when(repo.save(any())).thenAnswer(inv -> inv.getArgument(0));
service.cancel(42L);
verify(repo).save(argThat(o -> o.status() == CANCELLED));
}
@Test void refusesToCancelShippedOrder() {
when(repo.findById(43L)).thenReturn(Optional.of(new Order(43L, SHIPPED)));
assertThrows(IllegalStateException.class, () -> service.cancel(43L));
verify(repo, never()).save(any());
}

Notice two things. The stubbing is repeated in every test, with small variations, and each test describes the repository's behaviour again from scratch. And the tests verify calls, save() with an argument matcher, so they encode how the service talks to the repository. If we change the service to use a custom updateStatus() query instead of findById() and save(), every one of these tests fails, although the behaviour is unchanged.

2Rewriting the Tests With a Fake

A fake repository is a real implementation that keeps orders in a map. It is written once and behaves consistently in every test: what we save, we can find, and what we did not save is absent.

Java
class InMemoryOrderRepository implements OrderRepository {
private final Map<Long, Order> rows = new ConcurrentHashMap<>();
public Optional<Order> findById(Long id) { return Optional.ofNullable(rows.get(id)); }
public Order save(Order o) { rows.put(o.id(), o); return o; }
public int updateStatus(Long id, Status s) {
return rows.computeIfPresent(id, (k, o) -> o.withStatus(s)) == null ? 0 : 1;
}
}
@Test void cancelsOpenOrder() {
repo.save(new Order(42L, OPEN));
service.cancel(42L);
assertEquals(CANCELLED, repo.findById(42L).orElseThrow().status()); // check the state
}
@Test void refusesToCancelShippedOrder() {
repo.save(new Order(43L, SHIPPED));
assertThrows(IllegalStateException.class, () -> service.cancel(43L));
assertEquals(SHIPPED, repo.findById(43L).orElseThrow().status()); // unchanged
}

The tests now read like a description of behaviour: given an open order, cancelling it leaves it cancelled. The setup is ordinary use of the repository, not a script of answers.

3Why State-Based Tests Survive Refactoring

A test that checks state asks 'what is true after the action?'. A test that verifies calls asks 'which methods did the code call, with which arguments?'. The first question has the same answer however the service is implemented; the second changes with every refactoring. When we switch the service from findById() plus save() to updateStatus(), the fake-based tests still pass, because the fake implements both ways and the final state is the same. That is the main argument for fakes: they let tests pin down behaviour without pinning down implementation.

The same refactoring, two kinds of test
Change in the serviceMock-based testsFake-based tests
findById + save -> updateStatusfail: expected calls changedpass: state is the same
Add a cache before findByIdmay fail on verify countspass
Real bug: status not changedfailfail
New repository method neededstub it in each testimplement once in the fake

4Keeping the Fake Honest With a Contract Test

A fake is only useful if it behaves like the real implementation. If the real repository returns orders sorted by date and the fake returns them in map order, tests pass against the fake and the code fails in production. Fakes also need maintenance: each new repository method must be added to the fake.

The standard way to keep a fake honest is a contract test: an abstract test class that describes the repository's behaviour, with one subclass for the fake and one for the real implementation running against a real database, for example with Testcontainers. Both must pass the same tests.

Java
abstract class OrderRepositoryContract {
abstract OrderRepository repository();
@Test void findsWhatWasSaved() {
repository().save(new Order(1L, OPEN));
assertEquals(OPEN, repository().findById(1L).orElseThrow().status());
}
@Test void updateStatusReportsMissingRow() {
assertEquals(0, repository().updateStatus(99L, CANCELLED));
}
}
class InMemoryOrderRepositoryTest extends OrderRepositoryContract { // fast, every build
final OrderRepository repo = new InMemoryOrderRepository();
OrderRepository repository() { return repo; }
}
@Testcontainers @DataJpaTest
class JpaOrderRepositoryTest extends OrderRepositoryContract { // real PostgreSQL
@Autowired OrderRepository repo;
OrderRepository repository() { return repo; }
}
Step throughHow the pieces fit
  1. Service testsmany, fast, use the fake
  2. Contract testssame tests run against fake and real repository
  3. Fake repository | JPA repositoryin memory | PostgreSQL in a container

3 layers, from the top down. Step through them one at a time.

Now a difference in behaviour shows up as a failing contract test, and the fake can be fixed before it misleads anyone.

5Where Mocks Still Win

Fakes are not always better. For collaborators whose whole purpose is a side effect, such as an email sender, a payment gateway or an event publisher, the interaction is the behaviour, and verifying the call is the most direct test. A fake email sender that collects messages in a list works too, but for one or two checks verify(mailer).sendWelcome(email) is simpler. Mocks are also the easy choice for collaborators used by only a few tests, where writing and maintaining a fake costs more than it saves, and for simulating rare failures, such as a timeout from a third-party API, with a single thenThrow.

So the rule of thumb we use is: fakes for collaborators that hold state and are used by many tests, especially repositories and caches; mocks for side-effecting collaborators and for one-off failure cases.

6Follow-up questions

Isn't an in-memory database like H2 also a fake?

In a sense, yes: it is a working, lightweight replacement for the real database. But it differs from PostgreSQL in SQL dialect, locking and constraint behaviour, so tests can pass on H2 and fail in production. For repository tests, a real database in a container is more faithful; an in-memory fake at the repository interface is better for fast service tests.

Who should own the fake?

Ideally the team that owns the real implementation, shipped next to it, for example in a test-fixtures artifact. Then the fake and the contract test change together with the real code, and every consumer uses the same honest fake instead of writing its own.

7Conclusion

In this answer, we compared repeated Mockito stubs with an in-memory fake for service tests. A fake gives many tests the same consistent behaviour without repeated stubbing, and because the tests then check state rather than calls, they survive refactorings such as changing the queries a service uses. The cost is maintenance and the risk of a fake that behaves differently from the real thing, which a contract test run against both implementations controls. Mocks remain the right choice for verifying side-effecting collaborators and for one-off failure cases.

What to say in the interviewAbout 90 seconds aloud

Open with

I prefer a fake when a collaborator holds state and many tests depend on it, a repository being the classic case. With mocks, every test stubs findById, save and so on for exactly the calls the service makes, so the same setup is repeated with variations, and tests often verify those calls.

Then, if they want more

That ties the tests to the implementation: if I refactor the service to use an updateStatus query instead of find and save, every test breaks, although behaviour is unchanged. An in-memory fake backed by a map is written once and behaves consistently: what I save, I can find.

Tests then check the resulting state, like the order being cancelled, and they survive that kind of refactoring. The cost is that the fake must be maintained and must behave like the real repository, so I write a contract test, an abstract test class run against both the fake and the real implementation on a Testcontainers database.

If they diverge, the contract test fails. I would still use mocks for side-effecting collaborators such as an email sender or a payment gateway, where the call itself is the behaviour and verify is the most direct check, and for simulating rare failures like a timeout.

So: fakes for stateful collaborators shared by many tests, mocks for side effects and one-offs.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "When would you prefer a fake (for example an in-memory repository) over Mockito mocks in...": https://scrivio-interview-library.netlify.app/java/mocking/758d7b39bc/