Stubs
Info
A stub contains no logic; it only
return
s a predetermined value or an object (we stub thereturn
value).
Use Case
Stubs can be used when you need an object to return specific values to get your code under test into a certain state. Since we define the function’s behavior inline within the test, stubbing allows us to simulate a wide variety of
return
values orerror
s that might not be possible to trigger from a real implementation or a fakes.
To ensure its purpose is clear, each stubbed function should have a direct relationship with the test’s assertions1. As a result, a test typically should stub out a small number of functions because stubbing out many functions can lead to tests that are less clear.
A mocking framework is often a convenient way to reduce boilerplate of writing stubs.
Issues with Stubbing
- Stubbing exposes implementation details and does not provide guarantees about the correctness of the code; therefore real implementations and fakes are preferred even when stubbing would be a good choice.
- Test that requires a lot of stubbing is an indicator that the system under test is way too complex, and requires refactoring.