Test Doubles: Stubs and Mocks
You'll learn how stubs and mocks help you isolate and verify component interactions in integration tests.
The Core Idea
When testing how components work together, you often need to replace real dependencies with test doubles—stand-ins that simulate real objects. Two crucial types are stubs and mocks:
- Stubs provide predefined responses to calls made during tests. They answer questions with scripted data.
- Mocks go further—they not only provide responses but also verify that specific interactions happened (which methods were called, with what arguments, how many times).
Think of a stub like a recorded message on an answering machine: it gives you the same answer every time. A mock is like a security camera that also records what happened: who called, when, and what they said.
When to Use Each
Use stubs when you need to:
- Simulate a database returning specific test data
- Fake an external API response
- Provide consistent responses without caring if the method was called
Use mocks when you need to:
- Verify a logger was called with the correct error message
- Ensure a payment gateway's
processPayment()method was invoked exactly once - Confirm method call order or specific parameters were passed
In Integration Testing
During integration testing, you've already verified individual components with unit tests. Now you're testing interactions. Stubs replace components you don't want to test (like external services), while mocks verify that your integrated components communicate correctly—checking the "conversation" between them actually happened as expected.
Key Takeaway: Stubs provide controlled responses for predictable testing; mocks verify expected interactions actually occurred, making them essential for confirming components integrate correctly.