Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Explain the difference between a stub, a mock, a spy and a fake, with a Java example of each.

All four are test doubles, objects that stand in for a real collaborator in a test. A stub returns canned answers and the test checks the result; a mock records the calls it receives so the test can verify the interaction; a spy wraps a real object and runs its real methods unless we stub one; and a fake is a working but lightweight implementation, such as an in-memory repository. In Mockito, an object made with mock() acts as a stub or a mock depending on how we use it, and spy() creates a spy.

Why this question is asked

These four words are used loosely in everyday conversation, and many developers call everything a mock. Interviewers ask for the difference because the distinction is really about what a test checks: the result of the code, or the way it talks to its collaborators. Choosing the wrong kind of double is one of the main reasons test suites become brittle. In this answer, we will set up a small service, then write a test with each kind of double in turn, look at what each one checks, and finish with how Mockito's API maps onto the four terms.

1A Quick Recap of Test Doubles

When we unit test a class, we want to test that class alone, not the database or the mail server it uses. So we replace each collaborator with a test double, the general name for any object that takes the place of a real one in a test, the way a stunt double stands in for an actor. The four kinds differ in how much they do and what the test learns from them.

Our example is a service that registers a user: it checks whether the email is taken, saves the user, and sends a welcome email.

Java
interface UserRepository {
boolean existsByEmail(String email);
User save(User user);
Optional<User> findByEmail(String email);
}
interface Mailer { void sendWelcome(String email); }
class RegistrationService {
private final UserRepository users; private final Mailer mailer;
RegistrationService(UserRepository users, Mailer mailer) { this.users = users; this.mailer = mailer; }
boolean register(String email) {
if (users.existsByEmail(email)) return false;
users.save(new User(email));
mailer.sendWelcome(email);
return true;
}
}

2A Stub: Canned Answers, Check the Result

A stub answers calls with values we prepared, and nothing more. We use it when the collaborator provides input to the code under test, and the test checks what the code does with that input.

Java
@Test
void refusesTakenEmail() {
UserRepository users = mock(UserRepository.class);
when(users.existsByEmail("ann@acme.com")).thenReturn(true); // canned answer
RegistrationService service = new RegistrationService(users, mock(Mailer.class));
assertFalse(service.register("ann@acme.com")); // we check the result
}

Notice that the test never asks how the repository was used. It only checks the return value. That makes it robust: if the service later calls existsByEmail() through a cache or a different method, the test still passes as long as the result is right.

3A Mock: Record Calls, Verify the Interaction

Some behaviour has no result to check. Sending a welcome email returns nothing; its whole effect is the call to the mailer. A mock records the calls it receives, so the test can verify that the expected interaction happened.

Java
@Test
void sendsWelcomeEmail() {
UserRepository users = mock(UserRepository.class); // existsByEmail returns false by default
Mailer mailer = mock(Mailer.class);
new RegistrationService(users, mailer).register("bob@acme.com");
verify(mailer).sendWelcome("bob@acme.com"); // passes: the call happened once
verify(mailer, never()).sendWelcome("ann@acme.com"); // passes
}

Here the test checks the interaction itself. That is the right tool for side effects such as sending messages, publishing events or charging a card, where the call is the outcome. It is also the riskier tool, because verifying calls ties the test to how the code works, not only to what it achieves.

4A Spy: a Real Object With Selected Methods Replaced

A spy wraps a real object. Calls go to the real methods, and the spy records them, unless we replace a particular method with a stub. It is useful when we want almost all of the real behaviour and need to change or observe only one part, often in legacy code.

Java
@Test
void spyRecordsRealCalls() {
List<String> sent = spy(new ArrayList<String>());
sent.add("bob@acme.com"); // the real add() runs
System.out.println(sent.size()); // 1: the real size()
doReturn(100).when(sent).size(); // replace one method
System.out.println(sent.size()); // 100
verify(sent).add("bob@acme.com"); // the spy also recorded the call
}

Notice the doReturn(...).when(...) form for stubbing. On a spy, the usual when(spy.size()) would call the real method while setting up the stub, which can fail or have side effects, so doReturn is the safe form.

5A Fake: a Working Lightweight Implementation

A fake is a real implementation of the interface, written for tests, that takes a shortcut, usually keeping data in memory. It has behaviour, not scripted answers: what we save, we can find again.

Java
class InMemoryUserRepository implements UserRepository {
private final Map<String, User> byEmail = new HashMap<>();
public boolean existsByEmail(String email) { return byEmail.containsKey(email); }
public User save(User user) { byEmail.put(user.email(), user); return user; }
public Optional<User> findByEmail(String email) { return Optional.ofNullable(byEmail.get(email)); }
}
@Test
void registersOnlyOnce() {
var users = new InMemoryUserRepository();
var service = new RegistrationService(users, mock(Mailer.class));
assertTrue(service.register("cy@acme.com")); // true
assertFalse(service.register("cy@acme.com")); // false: the fake remembers the first save
assertTrue(users.findByEmail("cy@acme.com").isPresent()); // we check state, not calls
}
The four doubles side by side
DoubleWhat it doesWhat the test checksMockito
Stubreturns canned answersthe result of the codemock() + when()
Mockrecords callsthe interaction, via verify()mock() + verify()
Spyreal object, some methods replacedreal behaviour plus callsspy() + doReturn()
Fakeworking simplified implementationthe resulting statea hand-written class

The test checks the state of the world after the action, not the calls that produced it. No stubbing was needed for the second call to return false; the fake simply behaved like a repository.

6How Mockito Maps to the Four Terms

Mockito has no separate stub type. An object created with mock() is a stub when we only give it answers with when(...).thenReturn(...), and a mock when we check it with verify(...). The same object can be both in one test, which is why the terms blur in practice. spy() creates a spy around a real instance. Fakes are not something Mockito creates; we write them, or use ones that libraries provide, such as an in-memory database or a fake clock built with Clock.fixed().

So when someone says 'mock the repository', it is worth asking whether the test needs an answer from it, which is a stub, or needs to check a call to it, which is a mock. The answer decides whether a verify belongs in the test at all.

7Follow-up questions

What is a dummy?

A dummy is the simplest double of all: an object passed only to satisfy a parameter list and never actually used. In the stub test above, mock(Mailer.class) is effectively a dummy, because register() returns before reaching the mailer. Gerard Meszaros's test double vocabulary lists dummy, stub, spy, mock and fake.

Should I verify calls on a stub?

Usually not. If a collaborator only provides data, verifying that it was called duplicates what the result already proves and makes the test break when the implementation changes. Verify calls only for interactions that are themselves the behaviour, such as side effects.

8Conclusion

In this answer, we saw that stubs, mocks, spies and fakes are all test doubles that differ in what they do and what the test checks. A stub provides canned answers and the test checks the result; a mock records calls so the test can verify an interaction; a spy wraps a real object and replaces only selected methods; and a fake is a working lightweight implementation that lets the test check state. In Mockito, mock() serves as a stub or a mock depending on use, spy() creates a spy, and fakes are classes we write.

What to say in the interviewAbout 80 seconds aloud

Open with

All four are test doubles, objects that replace a real collaborator so we can test one class on its own. A stub just returns canned answers. For example, when(users.existsByEmail("ann")).thenReturn(true), and then I assert that register returns false.

Then, if they want more

The test checks the result, not how the repository was called. A mock records the calls it receives, so the test can verify an interaction. That is right when the call is the behaviour, like verify(mailer).sendWelcome(email), because sending an email has no return value to check.

A spy wraps a real object: the real methods run unless I stub one, and calls are recorded. I use spy(new ArrayList<>()) style spies mainly with legacy code, and I stub them with doReturn().when(), because when(spy.method()) calls the real method. A fake is a working, simplified implementation, like an in-memory repository backed by a HashMap.

What I save, I can find again, so the test checks the resulting state rather than calls. In Mockito there is no separate stub class: an object made with mock() is a stub if I only give it answers and a mock if I verify it. spy() creates spies, and fakes are classes I write myself.

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 "Explain the difference between a stub, a mock, a spy and a fake, with a Java example of...": https://scrivio-interview-library.netlify.app/java/mocking/7caebb4d78/