Mock Objects and Behaviour Verification
Mock objects stand in for collaborators and let a test assert which calls were made, a style that isolates the unit but couples tests to implementation.
Definition
A mock object is a test double that records the calls it receives and can be programmed with expectations, so a test verifies interactions rather than only final state.
Context and scope
It is used to isolate code from slow or unreliable collaborators such as networks, clocks, and third-party services.
Common misconceptions
- mocks and stubs are the same thing
- mocking every collaborator always makes tests more robust
Anti-patterns
- mocking so many collaborators that the test mirrors the implementation
- asserting an exact call sequence that a harmless refactor breaks
Related concepts
Related examples
Authoritative source
Definition
A mock object is a test double that records the calls it receives and can be programmed with expectations, so a test verifies interactions rather than only final state.
It is used to isolate code from slow or unreliable collaborators such as networks, clocks, and third-party services. Compared to simpler alternatives, this concept fits best when the trade-off it represents is the one the system actually cares about.
When to use it
A common use case is applying it at the boundary where the cost of getting it wrong is highest, and the scenario usually involves a concrete guarantee the system must uphold. Unlike an ad hoc approach, it makes that guarantee explicit, reviewable, and testable.
How it works
A stub returns canned answers, but a mock additionally asserts interaction, so overuse shifts the test’s focus from behaviour to internal wiring.
Tests that lock in call order and argument shapes resist refactoring, because any internal reorganisation fails tests even when the outcome is unchanged.
Trade-offs and alternatives
Prefer mocks at architectural boundaries and use real implementations for pure logic, so the test still says something about the system’s observable behaviour. The main drawback is the extra complexity it introduces, so the benefit should clearly outweigh that cost before a team adopts it.
Common misconceptions
A persistent misconception is that mocks and stubs are the same thing. Another is that mocking every collaborator always makes tests more robust. For example, an engineer who assumes otherwise may design around a guarantee that does not actually exist, which only becomes obvious under load or failure.
Anti-patterns to avoid
Two recurring anti-patterns are to mocking so many collaborators that the test mirrors the implementation and to asserting an exact call sequence that a harmless refactor breaks. Both tend to surface as hard-to-debug production issues rather than obvious test failures. Related concepts include Golden Master Testing, Test Flakiness Metrics, Accessibility Tree Testing.