Mocks, stubs, and fakes: the differences that matter
Dummy, stub, spy, mock and fake are not synonyms. What each test double does, with Vitest and Mockito examples, and when to verify state or behavior.
You open the pull request; CI was green yesterday and today it's red. Nobody touched the code. The failing test calls the real payment API, and the gateway was down for two minutes. On the other side of the same codebase, a colleague complains that he "mocked everything and the test passes, but it tests nothing": he refactored the whole function from the inside and no test complained. Both problems share a root, which is confusion about which kind of test double to use and when.
This post separates dummy, stub, spy, mock and fake using the definitions of the people who coined the terms, shows each one in code that runs (Vitest, Sinon and Mockito), explains the real divide between them, which is verifying state versus verifying behavior, and gives a firm opinion on when to use each.
Test double: the umbrella term
"Test double" is Gerard Meszaros's term, from the book xUnit Test Patterns (2007), for any object you put in place of a real dependency during a test. The analogy is the stunt double in film: someone who stands in for the actor in the dangerous scene. Martin Fowler popularized the vocabulary in the article Mocks Aren't Stubs. Day to day everybody calls everything a "mock", and the conversation turns into noise.
Fowler's definitions, which follow Meszaros's, fit in one table:
| Type | What it does | Has its own logic? | How the test verifies | Example |
|---|---|---|---|---|
| Dummy | Only fills a parameter; never actually used | No | Not verified | Empty logger passed to satisfy a signature |
| Stub | Returns canned answers to calls made during the test | No, just fixed values | State: you check the result of the code under test | Repository that always returns user 7 |
| Spy | A stub that also records how it was called | No | Behavior, with assertions after the action | Notifier that records the messages it received |
| Mock | Pre-programmed with expectations about the calls it should receive | No | Behavior: the mock checks itself in verify() |
Mailer that requires send once with certain arguments |
| Fake | Actually working implementation that takes a shortcut | Yes | State | In-memory repository instead of Postgres |
Fowler sums up the central difference like this: mocks always use behavior verification, while a stub can go either way; a stub used for behavior verification is what Meszaros calls a test spy. That is why the order I use here is dummy, stub, spy, mock and fake: a spy is a stub that records, a mock is a spy whose expectations were declared up front, and a fake belongs to another family, the simplified real implementations.
Dummy: it only fills a parameter
A dummy exists to satisfy a method signature. You have to pass something, but that argument is never used on the path the test exercises.
const dummyLogger = { log() {} };
expect(processOrder({ items: [1, 2] }, dummyLogger)).toBe(2);
If processOrder only logs when the order is empty, in this scenario dummyLogger is there just so the call works. You verify nothing on it. Sometimes null will do, but in typed code an explicit dummy is cleaner and makes the intent clear to whoever reads the test later.
Stub: returns a canned answer
A stub returns fixed values for the calls made during the test. It feeds the code under test with controlled data, period. You don't ask whether it was called; you use what it returns.
const userRepoStub = { findById: () => ({ id: 7, plan: "free" }) };
expect(checkout(userRepoStub, 7).discount).toBe(0); // verifies STATE
// the same stub with Vitest (or Jest, replacing vi with jest)
const findById = vi.fn().mockReturnValue({ id: 7, plan: "pro" });
expect(checkout({ findById }, 7).discount).toBe(10);
The assertion looks at the result (discount), not at the interaction with the stub. That is state verification: given this input, what is the output? A stub is perfect for forcing paths: a user with no plan, an empty list, an API error. You program the answer and watch what the system does with it.
Spy: records the calls so you can check later
A spy is a stub that also records how it was called: how many times, with which arguments. The assertion comes after the action, in the body of the test.
const notifier = { onError: vi.fn() };
runJob(() => { throw new Error("gateway timeout"); }, notifier);
expect(notifier.onError).toHaveBeenCalledTimes(1);
expect(notifier.onError.mock.calls[0][0]).toMatch(/timeout/);
A useful variation is spying on a method that already exists without replacing it. vi.spyOn(object, "method") (or jest.spyOn) records the calls and, by default, keeps running the original implementation:
const repo = new InMemoryUserRepo();
const saveSpy = vi.spyOn(repo, "save");
register(repo, { send() {} }, "bia@x.com");
expect(saveSpy).toHaveBeenCalledWith({ id: "bia@x.com", email: "bia@x.com" });
expect(repo.findById("bia@x.com")).not.toBeNull(); // the original save ran
Mock: expectations declared up front, checked at the end
Here the philosophy changes. A mock is pre-programmed with expectations about the calls it should receive. It isn't there to return data; it's there to check it was used the agreed way. If the expected call doesn't happen, or happens with the wrong arguments, the test fails. The purest form of this in JavaScript is sinon.mock:
import sinon from "sinon";
const mailer = { send() {} };
const mailerMock = sinon.mock(mailer);
mailerMock.expects("send").once().withArgs({ to: "ana@x.com", template: "welcome" });
register(new InMemoryUserRepo(), mailer, "ana@x.com");
mailerMock.verify(); // throws if "send" wasn't called exactly like this
That verify() at the end is the mock's signature. You don't look at the system's state; you assert that a specific interaction happened. That is behavior verification: did the code talk to the dependency the agreed way? It makes sense when the effect of the code is the external call itself (sending an email, publishing an event, charging a card) and there is no meaningful return value to inspect.
Fake: a lightweight implementation that works
A fake has real logic: it is a working implementation, just simplified and unfit for production. The classic example is the in-memory repository, which keeps records in a Map instead of going to Postgres but behaves like a repository.
class InMemoryUserRepo {
#users = new Map();
save(u) { this.#users.set(u.id, u); }
findById(id) { return this.#users.get(id) ?? null; }
}
The difference from a stub: a stub always returns the same thing and has no memory; a fake has state that evolves. If you save and then look up, the fake returns what you saved. That makes it great for flows with several chained operations without spinning up a database, and it is the kind of double that hexagonal architecture uses in use case tests. Verification is still about state: you act, then inspect the result.
All the JavaScript examples in this post live in a test file I ran with Vitest 3.2 and Sinon 19 on Node 22: 8 green tests, including one confirming that mailerMock.verify() throws when the expected call doesn't happen.
The real divide: state vs behavior
Forget the five names for a second. There are two ways to verify:
- State verification (stub and fake): you run the action and inspect the result or the final state. It doesn't matter how the code got there, only where it ended up.
- Behavior verification (spy and mock): you assert that certain calls happened, with certain arguments. What matters is how the code interacted with its dependencies.
The dummy belongs to neither: it isn't verified, it only takes a parameter's place. This is the distinction that changes how a test is designed. Memorizing names won't help if you don't first decide which kind of verification that test needs. If the question is what each test should assert, the sibling post unit tests: what to actually test tackles exactly that.
Jest, Vitest and Mockito: which function is which
Libraries don't follow the taxonomy strictly, and that is where much of the confusion comes from. The practical map:
| You want | Jest | Vitest | Mockito (Java) |
|---|---|---|---|
| Stub (canned answer) | jest.fn().mockReturnValue(x) |
vi.fn().mockReturnValue(x) |
when(m.method()).thenReturn(x) |
| Spy (record calls on a new function) | jest.fn() + toHaveBeenCalledWith |
vi.fn() + toHaveBeenCalledWith |
mock(Type.class) + verify(...) |
| Spy on an existing method, keeping the original | jest.spyOn(obj, "m") |
vi.spyOn(obj, "m") |
spy(realObject) |
| Mock with expectations declared up front | not built in (use Sinon: sinon.mock(...).expects(...)) |
same | not Mockito's style |
| Fake | you write the class | you write the class | you write the class |
Note that jest.fn()/vi.fn() is a stub and a spy at the same time, and that Mockito's mock(), despite the name, works spy-style: you verify after the action instead of declaring expectations first. Fowler already pointed out that a stub used for behavior verification is, in Meszaros's terminology, a spy. In Java:
// stub: canned answer + state verification
UserRepo repo = mock(UserRepo.class);
when(repo.planOf(7L)).thenReturn("pro");
assertEquals(10, discount(repo, 7L));
// behavior verification after the action
Mailer mailer = mock(Mailer.class);
register(mailer, "ana@x.com");
verify(mailer, times(1)).send("ana@x.com", "welcome");
// spy on a real object: the original method runs and the call is recorded
List<String> list = spy(new ArrayList<>());
list.add("a");
verify(list).add("a");
assertEquals(1, list.size());
That snippet runs as three JUnit 5 tests with Mockito 5.14 on Java 21; I ran it through Maven and it passed.
The over-mocking trap
This is where most of the pain lives. When you mock every collaborator and assert every call, the test becomes a mirror of the implementation. Swapped the order of two harmless calls? Red test. Extracted a private method? Red test. You didn't test observable behavior; you froze the code's internal structure. That is a test coupled to the implementation: fragile, expensive to maintain, and giving a false sense of coverage. The colleague who "mocked everything and the test tests nothing" fell into it.
The classic symptom: you refactor without changing observable behavior and half the suite breaks. A good test breaks when behavior changes, not when structure changes. When what you're doubling is the database, the answer often isn't a better double but an integration test against a real database, as the post on integration vs unit tests discusses; the balance between levels is in the testing pyramid.
My opinion after a lot of red CI
Prefer fakes and stubs. They test observable behavior and survive refactoring. Use spies and mocks sparingly, only when the interaction is the behavior: side effects with no return value, such as publishing an event, sending a notification or charging a card. And don't mock what you don't own: wrap the external API in an adapter of your own and double the adapter, never the third-party library directly. To make sure the adapter stays compatible with the real API, the answer is contract testing, covered in the post on contract testing between services; for mocking a whole HTTP API, see how to test APIs automatically.
Frequently asked questions
What is the difference between a mock and a stub?
A stub returns canned answers and the test checks the result of the code (state). A mock comes programmed with expectations about the calls it should receive and the test checks those calls happened (behavior). If what matters is the number that comes out, use a stub; if what matters is the call itself, such as sending an email, use a mock or a spy.
What is the difference between a mock and a spy?
Both verify behavior. With a spy you act first and assert on the recorded calls afterwards; with a mock the expectations are declared before the action and checked by the mock itself in verify(). In practice, jest.fn(), vi.fn() and Mockito's mock() all work spy-style.
What is the difference between a fake and a stub in practice?
A stub always returns the same answer and has no memory; a fake has state and real, simplified behavior. If the test saves a record and then looks it up expecting to get it back, you need a fake, because a stub wouldn't remember what was saved. For a single return value on a specific path, a stub is simpler and enough.
How do I know if I'm mocking too much?
Look at the assertions. If most of them are "call X happened" and almost none look at a result or state, the test is tied to the implementation. Try rewriting it to assert only the observable result; if you can't, maybe that dependency should be a fake. Rule of thumb: a test that breaks when you refactor without changing behavior is testing structure.
Choose the verification first, the name second
Test double is the umbrella: the dummy fills in, the stub answers, the spy records, the mock demands and the fake works. What decides a test's design is the choice between verifying state (stub, fake) and verifying behavior (spy, mock); decide that first and the double's name follows. When in doubt, go with a fake or a stub, keep spies and mocks for side effects, and don't double a dependency you don't control without wrapping it in an adapter first.
The editorial content ends here. When I need realistic data to feed a stub or populate a fake, such as a list of users with plausible names, emails and dates, I generate the JSON with the Quick Tools mock JSON generator instead of writing it by hand.
- 01 CPU Cores vs. Threads: What Actually Changes in Practice Understand the difference between CPU cores and threads and what actually changes for performance, multitasking, gaming, and development.
- 02 MIT, Apache, and GPL Licenses: Practical Differences for Developers MIT, Apache 2.0, and GPL are not the same thing. Understand permissive vs copyleft, patent protection, and compatibility before shipping code to production.