Test Stub
A test double that provides canned answers to calls made during a test, replacing real dependencies with predictable, pre-programmed responses.
Also known as: Stub, Method Stub, Test Stubs
Category: Software Development
Tags: testing, software-engineering, patterns, quality
Explanation
A test stub is a type of test double that provides canned answers to method calls made during a test. Stubs replace real dependencies with objects that return pre-programmed responses, making tests predictable and independent of external systems. Unlike mocks, stubs do not verify how they are called; they simply provide the data the code under test needs to execute.
Stubs support state-based verification: rather than checking which methods were called, the test checks the final state or return value of the code under test. This makes stub-based tests less coupled to implementation details compared to mock-based tests.
A common example is stubbing an API client. Instead of making real HTTP requests during a test (which would be slow, flaky, and require network access), a stub API client returns pre-defined responses. The test can then verify that the code correctly processes those responses.
Stubs can be configured to simulate different scenarios: returning specific values for happy paths, throwing exceptions for error paths, or returning different values on successive calls to test sequences. This makes them powerful for testing edge cases and error handling without needing to reproduce those conditions in real systems.
In Gerard Meszaros's taxonomy, stubs sit between dummies (which are never used) and spies (which also record call information). A stub only provides outputs; it does not track inputs. However, many modern testing frameworks blur this distinction, and what they call a 'stub' may also provide spy-like recording capabilities.
Stubs can be created manually (hand-rolled stubs) or generated by mocking frameworks. Hand-rolled stubs are simple classes that implement the same interface as the dependency, with hardcoded return values. Framework-generated stubs are configured inline within the test, offering more flexibility but adding a framework dependency.
Related Concepts
← Back to all concepts