Intermediate LevelSoftware Engineering Principles
Compare Test Doubles: Mocks vs Stubs vs Spies vs Fakes vs Dummies.
❓ Interview Prompt: Compare Test Double taxonomy (Gerard Meszaros): Dummy objects, Test Stubs, Test Spies, Mock objects, and Fake implementations.
Distinguishing Gerard Meszaros' taxonomy of Test Doubles:
•
Dummy: Passed to satisfy parameters but never actually used or called.
•
Stub: Provides hardcoded canned answers to calls during tests.
•
Spy: Wraps a real object to record telemetry about calls made (arguments, invocation count).
•
Mock: Objects pre-programmed with explicit expectations about calls they are expected to receive. Fails test if expectations aren't met.
•
Fake: Working lightweight implementation unusable in production (e.g. In-Memory SQLite database).
Code Implementation Example
typescript
import { vi } from 'vitest';
// Test Spy: Tracks method calls on real object
const spy = vi.spyOn(console, 'log');
console.log('Hello');
expect(spy).toHaveBeenCalledWith('Hello');
// Test Fake: In-Memory repository implementation
class FakeUserRepository implements UserRepository {
private users = new Map<string, User>();
async save(u: User) { this.users.set(u.id, u); }
}💡Utilizing Test Spies and Fakes in unit tests.
🎯 Interview Key Takeaway
Choose appropriate test doubles: Stubs for input data, Mocks/Spies for behavior verification, and Fakes for lightweight subsystem emulation.
#Test Doubles#Mocks#Stubs#Spies#Intermediate
Back to all Software Engineering Principles Questions→