Course contentsShow
← Software Engineering
Lesson 476 of 1,93314. Test DoublesFree lesson

The Test Double Pyramid

Apply the preference order: real objects > fakes > stubs > spies > mocks, choosing simpler doubles when possible.

The Test Double Pyramid

You'll learn: How to choose the right type of test double by preferring simpler, more realistic options first.

Just like the Testing Pyramid suggests using more unit tests than end-to-end tests, the Test Double Pyramid provides a preference order for choosing test doubles in your tests.

The Hierarchy: Prefer Real Over Fake

The pyramid from most preferred (bottom) to least preferred (top) looks like this:

  1. Real objects (no test double at all)
  2. Fakes (working implementations)
  3. Stubs (canned responses)
  4. Spies (recording interactions)
  5. Mocks (verifying expected calls)

Why This Order?

Real objects give you the highest confidence because they test actual behavior. Use them whenever they're fast, simple, and don't have external dependencies.

Fakes come next because they provide working implementations that behave realistically, even if simplified. An in-memory database is better than stubbing every database call.

Stubs are further up because they only return pre-programmed responses without real logic. They're useful but less realistic.

Spies and mocks sit at the top because they couple your tests most tightly to implementation details. They verify how code interacts rather than what it produces, making tests fragile when refactoring.

Choosing Simpler Doubles

When you do need a test double, ask: "What's the simplest double that gives me confidence?" If a stub provides a canned response that's sufficient, don't reach for a mock. If you can use a fake in-memory implementation, prefer that over stubs.

Key Takeaway: Start with real objects whenever practical, and climb the test double pyramid only as needed—simpler doubles make tests more maintainable and less brittle.