Testdoubles: Stubs vs. Mocks vs. Fakes vs. Spys
This article is a glossary entry on testdoubles – including exam questions and tags.
In a Nutshell
- Stub: delivers predefined answers
- Mock: verifies interactions (expectations)
- Fake: simplified, functional implementation
- Spy: records calls (combines stub + mock)
Compact Technical Description
Stub
Returns fixed answers without verifying behavior. Good for stateless tests.
Mock
Checks whether specific methods are called with specific parameters. Useful when interactions are critical.
Fake
Working but simplified implementation (e.g., in-memory DB). Good for integration-like unit tests.
Spy
Records calls and enables later verification (hybrid of stub and mock).
Exam-Relevant Key Points
- Stub: predefined answers, no behavior verification
- Mock: define and verify expectations
- Fake: functional simplification (e.g., in-memory repo)
- Spy: record calls, verify later
- Usage rules: stub for state, mock for behavior, fake for complexity
- Frameworks: Mockito, unittest.mock, Jest
Core Components
- Stub (answers)
- Mock (expectations)
- Fake (simplified implementation)
- Spy (recording)
- Test isolation
- Framework usage
- Setup/teardown
- Assertions
- Verification
- Maintenance
Practical Example (Discount Service)
// Stub
DiscountPolicy stub = new DiscountPolicyStub(10); // always 10%
int rabatt = service.berechneRabatt(kunde, artikel);
// Mock
DiscountPolicy mock = mock(DiscountPolicy.class);
when(mock.getRabatt(kunde)).thenReturn(10);
verify(mock).getRabatt(kunde);
// Fake
InMemoryDiscountRepository fake = new InMemoryDiscountRepository();
fake.add(new Discount(kunde, 10));
// Spy
DiscountPolicySpy spy = new DiscountPolicySpy();
service.berechneRabatt(kunde, artikel);
assertEquals(1, spy.getCallCount());
Typical Exam Questions (with Short Answer)
- Difference between stub and mock? Stub delivers answers; mock verifies calls.
- When to use fake? When a functional simplification is needed (e.g., in-memory DB).
- What does a spy do? Records calls and allows verification later.
Most Important Sources
- https://martinfowler.com/articles/mocksArentStubs.html
- https://junit.org/junit5/docs/current/user-guide/
- https://testing.googleblog.com