Test Doubles Explained: Stubs, Mocks, Fakes, Spies, and Dummies
When you write a unit test, you rarely test code in a vacuum. Most real-world functions depend on databases, APIs, email services, or other components. Testing against real dependencies makes tests slow, flaky, and hard to control. Test doubles solve this problem.
A test double is any object that stands in for a real dependency during testing. Gerard Meszaros coined the term in his book xUnit Test Patterns, and he defined five distinct types. Most developers use "mock" to mean all of them—but that's imprecise and leads to confusion. Here's what each type actually means.
The Five Types of Test Doubles
1. Dummy
A dummy is passed around but never actually used. It satisfies a parameter requirement without contributing anything to the test.
// The logger is required by the constructor but irrelevant to this test
const dummyLogger = { log: () => {} };
const userService = new UserService(dummyLogger);
const result = userService.validateEmail("test@example.com");
expect(result).toBe(true);When to use: When a dependency is required by the interface but has no bearing on what you're testing.
2. Stub
A stub provides canned answers to calls. It returns predetermined responses without any logic. Stubs are used to control indirect input—the data your code receives from its dependencies.
const stubUserRepository = {
findById: (id) => ({ id, name: "Alice", email: "alice@example.com" })
};
const userService = new UserService(stubUserRepository);
const user = await userService.getUser(42);
expect(user.name).toBe("Alice");The stub always returns Alice regardless of what ID you pass. You control the scenario by controlling what the stub returns.
When to use: When you need to simulate specific states or responses from a dependency—success, not-found, error—without the real implementation.
3. Spy
A spy records calls made to it. You can assert after the fact whether a method was called, how many times, and with what arguments. Spies wrap real implementations or stand-alone, but they capture invocation data.
const emailService = {
send: jest.fn() // Jest spy
};
const orderService = new OrderService(emailService);
await orderService.placeOrder({ userId: 1, items: ["Widget"] });
expect(emailService.send).toHaveBeenCalledOnce();
expect(emailService.send).toHaveBeenCalledWith(
expect.objectContaining({ to: "user@example.com" })
);When to use: When you want to verify that your code triggered a side effect—sent an email, wrote a log, fired an event—without caring about the side effect's implementation.
4. Mock
A mock is pre-programmed with expectations. Unlike a spy, which records and lets you assert afterward, a mock verifies behavior during the test. If the expected call doesn't happen, the mock fails the test itself.
// Mockito-style (Java)
UserRepository mockRepo = mock(UserRepository.class);
when(mockRepo.findById(42)).thenReturn(new User(42, "Alice"));
UserService service = new UserService(mockRepo);
service.getUser(42);
// Fails the test if findById was never called
verify(mockRepo).findById(42);The distinction from a spy: the mock specifies what should happen upfront. The spy lets you observe what did happen afterward.
When to use: When the interaction with a dependency is the thing you're testing—not the result, but whether the right method was called in the right way.
5. Fake
A fake has a real working implementation—but one that takes shortcuts inappropriate for production. An in-memory database is the classic example.
class InMemoryUserRepository {
constructor() {
this.users = new Map();
}
async save(user) {
this.users.set(user.id, user);
}
async findById(id) {
return this.users.get(id) || null;
}
}
// Tests run against this fake—fast, deterministic, no real DB
const repo = new InMemoryUserRepository();
const service = new UserService(repo);
await service.createUser({ id: 1, name: "Bob" });
const user = await service.getUser(1);
expect(user.name).toBe("Bob");When to use: When stubbing would be too complex (lots of methods, stateful behavior) and the real dependency is too expensive. Fakes are especially useful for repositories, caches, and message queues.
Summary Table
| Type | Has logic? | Records calls? | Pre-programmed expectations? | Common use case |
|---|---|---|---|---|
| Dummy | No | No | No | Fill required params |
| Stub | Minimal | No | No | Control inputs |
| Spy | Optional | Yes | No | Verify outputs/side effects |
| Mock | No | Yes | Yes | Verify interactions |
| Fake | Yes | No | No | Replace complex dependencies |
The Language Problem
Most modern testing frameworks blur these distinctions. Jest's jest.fn() is technically a spy—it records calls and lets you assert on them. But people call them "mocks." Sinon's sinon.mock() creates mock objects with expectations. Mockito is named after mocks but is used for stubs just as often.
The terminology matters less than the intent. Ask yourself:
- Am I controlling what comes into my code? → Stub
- Am I checking what my code sends out? → Spy or Mock
- Am I replacing a complex dependency with a simpler one? → Fake
- Am I just satisfying a constructor? → Dummy
Where HelpMeTest Fits
Test doubles are great for unit tests, but they introduce a gap: your fakes and stubs might not match how your real dependencies behave. End-to-end tests close that gap by running against real systems.
HelpMeTest lets you write end-to-end tests in plain English—no mocks, no stubs, just real browser behavior against your actual application. When your unit tests pass but users report bugs, HelpMeTest catches what test doubles can't.
Key Takeaways
- Dummy: placeholder, never used
- Stub: returns canned data, controls inputs
- Spy: records calls, verifies outputs
- Mock: pre-programmed expectations, verifies interactions
- Fake: real logic, production shortcut
Precise terminology leads to clearer test design. When a teammate says "mock the database," now you can ask: do you mean a stub that returns fixed data, a fake with in-memory logic, or a mock that verifies specific calls were made?