A test stub is a minimal replacement for a real dependency that returns predefined, canned responses to the calls made by the code under test. In software testing and programming, a stub lets a developer exercise one unit of logic without contacting a database, a network service, the system clock or any other component that is slow, unreliable or not yet built.
Stubs belong to the wider family of test doubles, alongside fakes, spies, mocks and dummy objects. What sets a stub apart is its purpose: it supplies indirect inputs to the code under test, and the test then checks the result or the state of that code, not the way the stub itself was called.
How a test stub replaces a dependency
A test stub works by substituting an object that shares the dependency’s interface but contains no real behavior. When the code under test calls a method on the stub, the stub returns a value that the test author chose in advance, such as a fixed exchange rate, an empty list or a specific exception.
The substitution requires a seam, a place where the dependency can be swapped without editing the production code. The most common seam is dependency injection: the class receives its collaborators through a constructor or parameter, so a test can pass a stub instead of the real implementation. Other seams include configuration switches, module patching in dynamic languages and link-time substitution in compiled languages such as C.
The following table lists the main ways to introduce a stub and the conditions that favor each one.
| Technique | How the stub enters | Typical environment |
|---|---|---|
| Constructor injection | Passed as an argument when the object is created | Java, C#, TypeScript services |
| Parameter injection | Passed directly to the function under test | Functional code, small utilities |
| Hand-written class | A small class implements the same interface | Any statically typed language |
| Framework stubbing | A library generates the object at run time | Mockito, unittest.mock, Sinon |
| Monkey patching | A module attribute is replaced during the test | Python, JavaScript, Ruby |
| Link-time substitution | A different object file is linked into the test binary | C and embedded firmware |
Kinds of test stubs and their behavior
Not every stub simply returns one constant. Practitioners distinguish several variants according to how much logic the stub contains and what it is meant to provoke in the code under test.
| Variant | Behavior | Typical use |
|---|---|---|
| Responder stub | Returns a fixed valid value | Testing the normal path |
| Saboteur stub | Throws an error or returns a failure code | Testing error handling and retries |
| Sequenced stub | Returns different values on successive calls | Testing polling, pagination, retry loops |
| Conditional stub | Chooses the answer from the input arguments | Testing branching on lookup results |
| Temporary stub | Placeholder for code not yet written | Top-down integration of new modules |
The saboteur stub is especially valuable because real failures, such as a timeout from a payment gateway, are hard to trigger on demand. A stub that raises the same exception makes the error path deterministic, so the recovery logic can be verified on every run.
The temporary stub has a longer history than the others. In top-down integration testing, higher-level modules are tested first, and the lower-level modules they call are represented by stubs until the real implementations exist. The mirror image, a test driver, calls a lower-level module from above when the higher layers are missing.
Test stub compared with mocks, fakes and other doubles
A test stub differs from a mock in what the test verifies. A stub feeds data into the code under test and the assertions examine the output, an approach called state-based verification. A mock carries expectations about which calls it should receive, and the test fails if those calls do not occur, which is behavior-based verification.
| Double | Main purpose | Verifies interactions |
|---|---|---|
| Dummy | Fills a required parameter that is never used | No |
| Stub | Provides canned answers as indirect input | No |
| Spy | Stub that also records calls for later inspection | After the fact |
| Mock | Preprogrammed with expected calls | Yes, by design |
| Fake | Working lightweight implementation, such as an in-memory database | No |
Many mocking libraries blur these lines, because the same generated object can act as a stub in one test and a mock in another. The distinction still matters for design: stubbing queries and mocking commands is a widely used rule. Calls that return data are stubbed, while calls whose side effect is the point of the test, such as sending an email, are verified as interactions.
When to use a stub in a test suite
A stub is the right choice when a dependency would make a unit test slow, nondeterministic or hard to set up. Typical candidates are remote APIs, databases, file systems, random number generators and the current time. Replacing them keeps unit tests in the range of a few milliseconds each, which allows thousands of them to run on every commit.
The decision table below summarizes how experienced teams choose between a stub and alternative approaches.
| Situation | Recommended choice | Reason |
|---|---|---|
| Code reads a value from an external service | Stub the service | Only the returned data affects the outcome |
| Code must send a notification | Mock or spy | The call itself is the expected result |
| Logic depends on the current date | Stub the clock | Removes time-dependent flakiness |
| Dependency is a simple pure function | Use the real code | A stub adds cost without benefit |
| Many tests need realistic data behavior | Fake implementation | Avoids repeating stub setup |
| Verifying the real database schema | Integration test | A stub cannot detect schema errors |
Stubs are configured inside the test or in a test fixture shared by several tests. Keeping the canned values close to the assertions makes each test readable as a self-contained story: given this input from the dependency, the code produces this output.
Limitations and common mistakes with stubs
The central risk of a stub is drift from the real dependency. A stub encodes the author’s assumption about how the dependency behaves, and if the real service changes its response format, every stubbed test keeps passing while production fails. Contract testing and a smaller set of integration tests exist largely to close this gap.
- Over-stubbing: replacing so many collaborators that the test only confirms the stubs return what they were told to return.
- Unrealistic canned data: values that the real system never produces, such as negative quantities or impossible dates, which hide genuine defects.
- Stubbing the class under test: partial stubs on the object being tested, which undermine the meaning of the test.
- Brittle argument matching: conditional stubs tied to exact arguments, which break when harmless refactoring changes a call.
- Missing failure stubs: testing only the happy path and never simulating timeouts, empty results or malformed responses.
A useful discipline is to stub only what you own through a thin adapter. Instead of stubbing a third-party HTTP client directly, the team wraps it in its own interface and stubs that interface, so the stubs describe the team’s domain rather than the library’s internal details.
In simple terms
A test stub is a stand-in that gives the same prepared answer every time it is asked. Imagine rehearsing a play before one actor has arrived. Someone reads that actor’s lines from a script so the others can practice their scenes. The reader is not the real actor, but the rehearsal can go on.
In programming, a piece of code often needs information from somewhere else, such as a bank, a weather service or a database. A stub pretends to be that source and hands back fixed information. This lets developers check whether their own code reacts correctly without waiting for, paying for or breaking the real system.
A practical example
A development team builds a checkout service for an online store that converts prices into the customer’s currency. The conversion code calls an external exchange-rate API, which is rate-limited, sometimes slow and returns values that change every minute. Tests that depend on it would be slow and unpredictable.
The team defines an ExchangeRateProvider interface and injects it into the checkout service. In unit tests, a responder stub returns a fixed rate of 0.92 for USD to EUR, so a 100.00 USD cart must show 92.00 EUR. A saboteur stub raises a timeout, and the test confirms that the service falls back to the last cached rate and logs a warning. A sequenced stub returns an error once and then a valid rate, which verifies the single automatic retry.
The suite of 40 checkout tests runs in under one second on every commit. A separate nightly contract test calls the real API to confirm the response format still matches the stubs. The outcome is fast, deterministic tests for the business logic, with drift from the real service caught within a day.