Stubs: Providing Canned Responses
What You'll Learn
You'll learn how to create stubs that return predetermined values to control test inputs without executing real dependencies.
The Core Idea
A stub is a test double that provides hardcoded answers to method calls made during tests. Unlike dummy objects (which do nothing), stubs actually respond when called—but with fixed, predictable data you define in advance.
Think of a stub like a movie set prop phone. When an actor "dials" it, they don't get a real connection—they get exactly the scripted response the scene needs. Similarly, a stub doesn't perform real work; it just returns the exact value you programmed it to return.
Why Use Stubs?
Stubs help you:
- Control test conditions: Force specific scenarios (success, failure, edge cases) without depending on external systems
- Speed up tests: Avoid slow operations like database queries or API calls
- Test in isolation: Verify your code's behavior independently of its dependencies
- Make tests deterministic: Get the same result every time, not random data from real services
The Difference from Dummies
While a dummy object exists only to fill parameter lists and is never actually used, a stub is called and returns values. Your test code depends on what the stub returns.
Common Stub Scenarios
You might stub:
- A database query that returns a specific user record
- An API client that returns a fixed weather forecast
- A date/time provider that always returns the same timestamp
- A file reader that returns predetermined content
Key Takeaway: Stubs provide canned, predetermined responses to method calls, letting you control exactly what your code receives from its dependencies during testing without executing real operations.