Partial Mocking and Spying on Real Objects
You'll learn when to mock only specific methods of a real object while preserving its actual behavior for others—and why this approach can be risky.
The Core Idea
Sometimes you want to test a class but only replace one or two of its methods, letting the rest work normally. This is called partial mocking or spying. Instead of creating a complete mock or fake, you take a real instance and selectively override specific methods.
Think of it like a stunt double in a movie: the actor performs most scenes themselves, but a professional handles the dangerous jumps. Similarly, your object does most of its real work, but you "stand in" for specific risky or inconvenient methods.
When You Might Use It
You might spy on a real object when:
- You need to verify a method was called, but want everything else to work normally
- One method has an external dependency (like network calls), but the rest is safe
- You're testing legacy code and can't easily refactor yet
The Associated Risks
Partial mocking is a code smell that often indicates design problems:
- Tight coupling: If you need to mock some methods but not others, your class may be doing too much
- Fragile tests: You're mixing real and fake behavior, making it harder to reason about what's actually being tested
- False confidence: Tests might pass while hiding real integration issues
Most of the time, if you need partial mocking, it's better to extract the problematic methods into a separate collaborator that you can fully mock or stub.
Key Takeaway:
Partial mocking lets you override specific methods while keeping real behavior for others, but it often signals that your class has too many responsibilities and would benefit from decomposition into smaller, more focused units.