Mock vs Stub — Explained with Examples
In this tutorial, you'll learn about Mock Vs Stub. We cover key concepts, practical examples, and best practices.
Mocks, stubs, fakes, and spies are test doubles that replace real dependencies in tests, each serving a different purpose in verification and isolation.
Test doubles are stand-ins for real objects during testing. The term was popularized by Gerard Meszaros in xUnit Test Patterns. Each type has a specific role.
The Four Types
Stub — provides canned answers to calls made during the test. Used when you need a consistent return value.
// Stub — returns fixed data
const userServiceStub = {
getUser: async (id) => ({ id, name: 'Alice', role: 'admin' })
};
Mock — records calls and verifies that specific interactions happened. Used when you need to assert behavior.
// Mock — verifies interactions
const emailServiceMock = {
send: jest.fn().mockResolvedValue(true)
};
// Test asserts that send() was called with expected args
test('sends welcome email on registration', async () => {
await registerUser('alice@example.com', emailServiceMock);
expect(emailServiceMock.send).toHaveBeenCalledWith(
'alice@example.com',
expect.stringContaining('Welcome')
);
});
Fake — a working implementation but simplified (e.g., in-memory database instead of real PostgreSQL).
// Fake — lightweight in-memory database
class InMemoryUserRepo {
constructor() { this.users = new Map(); }
async create(user) {
this.users.set(user.email, user);
return user;
}
async findByEmail(email) {
return this.users.get(email);
}
}
Spy — wraps a real object and records calls without replacing behavior.
// Spy — wraps real logger, records calls
const logger = new Logger();
const spy = jest.spyOn(logger, 'info');
doSomething(logger);
expect(spy).toHaveBeenCalledWith('Operation completed');
Real-World Analogy
Consider a flight simulator for pilot training:
- Stub — the control panel always shows altitude 30,000 ft (fixed data)
- Mock — records that the pilot pressed the "landing gear up" button (behavior verification)
- Fake — a simplified physics engine that simulates flight but isn't real aircraft software (working but simplified)
- Spy — a real altimeter with a recording of what it displayed (wraps real, records)
When to Use Each
| Double | Use When |
|---|---|
| Stub | You need a dependency to return specific values |
| Mock | You need to verify that specific methods were called |
| Fake | A real dependency is too slow or unavailable |
| Spy | You want real behavior plus call recording |
Related Terms
Unit Testing, TDD, Integration Testing
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro