Mocks: Verifying Expected Interactions
You'll learn how mocks differ from other test doubles by actively verifying that your code calls dependencies exactly as expected.
What Makes Mocks Special
While stubs and spies passively wait for you to check what happened, mocks are pre-programmed with expectations. You tell the mock upfront what should happen, and if your code doesn't interact with it exactly as specified, the test fails automatically—even without explicit assertions.
Think of it like a movie director's script: a stub is an actor who improvises their lines and you check the recording later. A mock is an actor who must deliver specific lines at specific times, or the whole scene is ruined immediately.
How Mocks Work
You set expectations on the mock before running your code:
- Which method should be called
- With what arguments
- How many times
- In what order (sometimes)
After your code runs, the mock verifies itself. If a required method wasn't called, or was called with wrong arguments, the mock fails the test.
When to Use Mocks
Mocks shine when you care deeply about how your code interacts with a dependency, not just the outcome. For example:
- Verifying an email service is called exactly once with the right recipient
- Ensuring a payment API receives specific transaction details
- Confirming a logger records critical error messages
They enforce behavior contracts between your code and its collaborators.
The Trade-off
Mocks create tighter coupling between tests and implementation details. Change how you call a dependency, and mock-based tests break—even if the behavior is still correct. Use mocks when the interaction protocol matters; use stubs when you only care about outcomes.
Key Takeaway: Mocks pre-verify that dependencies are called correctly, failing tests automatically when expected interactions don't occur—making them powerful for testing communication protocols but more brittle than stubs.