Skip to content
IRC-Coding IRC-Coding
Test Doubles Stub Mock Fake Spy Unit Tests

Test Doubles Explained: Stubs, Mocks, Fakes & Spys

Master test doubles: Stubs, Mocks, Fakes, and Spys. Learn when to use each with examples and best practices.

S

schutzgeist

2 min read

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

  1. Stub (answers)
  2. Mock (expectations)
  3. Fake (simplified implementation)
  4. Spy (recording)
  5. Test isolation
  6. Framework usage
  7. Setup/teardown
  8. Assertions
  9. Verification
  10. 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)

  1. Difference between stub and mock? Stub delivers answers; mock verifies calls.
  2. When to use fake? When a functional simplification is needed (e.g., in-memory DB).
  3. What does a spy do? Records calls and allows verification later.

Most Important Sources

  1. https://martinfowler.com/articles/mocksArentStubs.html
  2. https://junit.org/junit5/docs/current/user-guide/
  3. https://testing.googleblog.com
Back to Blog
Share:

Related Posts