Distinguishing Between Mock Types
You'll learn how to pick the right test double—stub, spy, mock, or fake—based on what you're trying to verify in your test.
The Core Idea
Test doubles aren't interchangeable. Each type serves a specific purpose:
Stubs answer questions. Use them when your code needs a response from a dependency, but you don't care how it was called. "When the database is asked for user #42, return this user object."
Spies observe and record. Use them when you need the real behavior plus want to verify something about how it was called. "Let the logger work normally, but let me check afterward if it logged an error."
Mocks enforce expectations. Use them when the interaction itself is what you're testing. "The email service must be called exactly once with this subject line, or the test fails."
Fakes implement simplified logic. Use them when you need realistic behavior without external dependencies. "This in-memory database works like a real one but doesn't persist anything."
Choosing the Right Double
Ask yourself: "What am I actually testing?"
- Testing that your code uses a result correctly? → Stub
- Testing that your code performs the right actions? → Mock
- Need to verify interaction after the test runs? → Spy
- Need realistic behavior across multiple tests? → Fake
The mistake beginners make is over-mocking: using mocks everywhere when stubs would be simpler. Mocks couple your tests to implementation details, while stubs focus on outcomes.
Key Takeaway: Choose stubs for returning values, mocks for verifying behavior, spies for recording interactions, and fakes for realistic lightweight implementations. Match the double to what you're actually testing.