When to Mock vs When to Use Real Implementations
You'll learn: How to decide whether to use test doubles or real objects in your tests, balancing speed and isolation against realistic behavior.
The Core Decision
Not every dependency needs to be mocked. The choice between using a mock (or other test double) and a real implementation depends on what you're testing and what gives you the most confidence.
Prefer Real Implementations When:
The Dependency is Fast and Simple
If an object is quick to create and has no side effects (like a value object or utility class), use the real thing. Mocking adds unnecessary complexity.
You Need Integration Confidence
Sometimes you want to verify that two components actually work together correctly. Using real implementations for these integration points gives you more realistic feedback.
The Logic is Critical
Testing with real implementations catches bugs in the actual code, not just in your assumptions about how it should behave.
Prefer Test Doubles When:
The Dependency is Slow
Database calls, network requests, or file I/O make tests sluggish. Stub or fake these to keep tests fast.
The Dependency is Non-Deterministic
Random number generators, current time, or external APIs produce unpredictable results. Stubs provide control.
You're Testing Error Scenarios
Mocks let you simulate failures (network timeouts, disk full) that are hard to trigger with real implementations.
You Need to Verify Interactions
When the behavior (that a method was called) matters more than the result, mocks verify those expectations.
Key Takeaway: Use real implementations by default for speed and simplicity; reach for test doubles when dealing with slow, unpredictable, or external dependencies, or when you need to verify specific interactions rather than outcomes.