Mocking, Stubbing, and Test Isolation Questions
Isolating the unit under test from its dependencies. Covers mocks, stubs, fakes, and spies, when to use test doubles versus real dependencies, and controlling external services and time. Includes designing for isolation so tests are fast, deterministic, and focused.
Give a decision rubric for when to mock an external dependency (a third-party API, a database, a cache) versus calling the real thing in a test. Name the factors your rubric weighs, and explain how the right answer can differ between a local development run, a CI pipeline, and a staging environment.
Sample Answer
Direct answer
Mock a dependency when calling the real one would make the test slow, nondeterministic, expensive, or unsafe to run repeatedly; call the real dependency when the test's whole purpose is to validate the integration itself, or when a fake would hide the exact behavior you're trying to verify.
Structured elaboration
A useful rubric weighs five factors together, not any single one in isolation:
- Speed: a network call to a real third-party service typically costs tens to hundreds of milliseconds; a thousand such tests would make the suite unusably slow. Mocking removes that cost.
- Determinism: real dependencies can be flaky (rate limits, transient errors, clock skew). A test that fails one run in twenty because of the real dependency, not because of a bug, teaches the team to ignore red builds.
- Cost: some real calls cost real money (a payment gateway, a paid data API) or consume a shared, limited quota (a sandboxed third-party account). Running them on every commit is not viable.
- Availability: local development and CI often can't reach an internal-only service, a VPN-gated system, or a partner's staging environment at all.
- Business risk: mocking a critical safety or compliance check (say, a fraud check before a payment) can mean the test never actually exercises the real decision logic, so a regression there ships silently.
Environment changes the answer: local development favors mocks for a fast inner loop; CI usually mixes a large mocked-unit-test layer with a smaller, real-dependency integration-test layer, run less frequently or gated separately; staging is often the first point where the real dependency should be exercised end-to-end, precisely because CI mocked it.
Worked example
A checkout service calls a fraud-scoring API. For the unit tests of the checkout logic (does it block the order when the score is above the threshold), mock the fraud API to return controlled scores like 0.95 and 0.10 so both branches are tested deterministically and instantly. For a smaller number of staging-only tests, call the real fraud API with known test accounts, because a mock can never tell you whether the real API's response schema or business logic changed. If the mock's shape silently drifted from the real API (say, the real API renamed a field from score to riskScore), only the staging test calling the real dependency would catch it.
Trade-offs and pitfalls
A rubric answer that only lists factors without weighing them together isn't complete: high business risk can outweigh speed and cost considerations, which is why safety-critical or compliance-relevant checks deserve at least a thin layer of real-dependency tests even if they're expensive and only run pre-release. The common mistake is mocking everything for speed and never re-validating that the mocks still match reality, which the mock's own definition can't protect against.
You are writing integration tests for a service that depends on a rate-limited third-party API. Propose a checklist of practices to keep the tests stable and safe to run in CI without exceeding the provider's rate limits or causing real side effects. Explain which parts of your checklist rely on mocking versus other techniques, and how you would categorize existing tests by how much they depend on that external dependency.
Sample Answer
Direct answer
Keep integration tests stable against a rate-limited third-party API by combining mocking for the bulk of tests, a small number of real calls that respect the provider's limits, circuit breakers and retries in the code under test itself, and a way to categorize tests by how much they actually depend on the external service, rather than treating "call the real API" and "mock it" as the only two options.
Structured elaboration
A practical checklist:
- Mock the dependency for the majority of tests: any test whose purpose is your own business logic, not the third party's real behavior, should not touch the real API at all.
- Throttle deliberately for the small number of tests that do call the real API: add explicit rate limiting or spacing in the test suite itself (not just relying on the provider's own limit response) so your CI run never approaches the provider's ceiling and never impacts their real operations.
- Use stubbing and replay for realistic failure scenarios: a controllable stub or a recorded-and-replayed real response lets you exercise rate-limit (429) or downtime (5xx/timeout) responses on demand, without needing the real provider to actually be rate-limiting or down at test time.
- Test your resilience mechanisms directly: circuit breakers, retries, and feature flags that gate a feature off if the dependency is unhealthy should have their own tests, using the stub to simulate the exact failure conditions those mechanisms exist to handle.
- Categorize tests by dependency: tag or group tests by which external dependency they touch and how (mocked-only versus real-call), so a provider outage or rate-limit change only threatens a known, small, clearly-labeled set of tests, and the team can quickly decide whether to skip that group temporarily without guessing which tests are affected.
Worked example
A weather-data integration has 40 tests total. 35 are mocked entirely and run on every commit. 5 are tagged @real_api and run only in a nightly job, spaced 2 seconds apart to stay well under the provider's per-minute rate limit and specifically chosen to validate things a mock cannot: that the real response schema still matches what the code expects, and that a real 429 response is handled by the circuit breaker exactly as designed. A separate stub-based test simulates a 429 explicitly to verify the circuit breaker opens after 3 consecutive failures, without needing the real provider to actually be rate-limiting at that moment.
Trade-offs and pitfalls
Treating rate-limit or intermittent third-party slowness purely as a "make it more reliable" problem and mocking everything removes the flakiness but also removes the team's only signal that the real integration still works; the categorization step (which tests actually call the real dependency) is what prevents that risk from becoming invisible. A checklist that never mentions respecting the provider's actual limits, only the test suite's own convenience, risks getting your test account rate-limited or banned, which is a self-inflicted outage of your own CI.
How do you test code that depends on the current time, such as token expiry or a scheduled task? Describe the tools and approaches you would use to make the test deterministic and safe from timezone or daylight-saving issues.
Sample Answer
Direct answer
Test time-dependent code (token expiry, scheduled tasks) by injecting or freezing the clock rather than letting the code call the system clock directly, so the test controls exactly what "now" is and the result is deterministic and safe from timezone or daylight-saving surprises.
Structured elaboration
- Clock injection: pass a clock (a function, an interface, or an object with a
now()method) into the code under test instead of callingdatetime.now()orSystem.currentTimeMillis()directly. In tests, supply a fake clock you fully control; in production, supply the real system clock. This is the most explicit and testable approach, and it composes well with dependency injection generally. - Freeze-time libraries: tools like Python's
freezegunor similar libraries in other languages monkeypatch the standard time functions for the duration of a test, so code that calls the system clock directly (without being refactored for injection) still becomes deterministic. Convenient when you can't change the production code's clock access. - Timezone and daylight-saving safety: always reason and assert in UTC internally, and only convert to a local timezone at the presentation boundary. Explicitly test boundary dates (a daylight-saving transition, a leap day, a year rollover) since these are exactly the inputs where naive "add N hours" or "add N days" arithmetic silently breaks.
Worked example
A token-expiry check computes is_expired = now() > issued_at + timedelta(hours=1). With a fake clock fixed at issued_at + 59 minutes, the test asserts is_expired is false; advancing the fake clock to issued_at + 61 minutes and asserting is_expired is true tests both sides of the boundary deterministically, with no real waiting and no flakiness from how fast the test happens to run.
Trade-offs and pitfalls
Freeze-time libraries are convenient but can hide a design smell: if a large codebase relies on monkeypatching the system clock everywhere because nothing was ever built to accept an injected clock, that's a sign the code should be refactored toward explicit clock injection over time, since it also makes production behavior (like clock skew across servers) easier to reason about. A subtler pitfall is testing only "normal" days; DST and leap-year boundaries are where naive time arithmetic actually breaks, and a suite with no tests near those boundaries can pass indefinitely while carrying a real bug.
Compare the main strategies for virtualizing an external service in tests: hand-written contract-based stubs, a standalone mock server generated from an API contract, and network-level record-and-replay of real traffic. For each, discuss maintenance overhead, fidelity to production behavior, and how it scales when many tests run in CI. How would you decide it is safe to rely on one of these instead of the real dependency?
Sample Answer
Direct answer
Contract-based stubs, generated mock servers, and record-and-replay virtualization trade off differently on maintenance cost, fidelity, and scalability: hand-written contract stubs are cheapest to write but drift fastest, a mock server generated from a real API contract stays truer to the interface with less manual upkeep, and record-and-replay captures real traffic faithfully but is the most brittle to any change in the real service.
Structured elaboration
- Hand-written contract-based stubs: a developer writes the expected request/response pairs directly. Cheap to start, fast to run, but nothing keeps them honest, if the real service's contract changes, the stub keeps returning the old shape and tests keep passing against a lie.
- Standalone mock server generated from an API contract (for example, from an OpenAPI spec) via a tool like WireMock: the mock server's shape is derived mechanically from a document that is, ideally, kept current alongside the real API. This reduces manual drift risk versus hand-written stubs, at the cost of needing the contract itself to be trustworthy and current, and some setup/startup cost since it's a separate running process rather than an in-process object. Configuring stateful scenarios (a resource that behaves differently on a second call) and keeping the generated stubs in sync with schema changes are the ongoing maintenance tasks.
- Network-level record-and-replay: real traffic is captured once against the actual service, then replayed verbatim in tests. Highest fidelity to actual real-world behavior at the moment of recording, but the most brittle over time: any change to the real service (even a benign one) can make the recording stale, and non-deterministic fields in the recorded response (timestamps, request ids) need explicit handling or the replay will fail on exact-match comparisons. In CI it scales about as well as an in-process stub, since replay usually reads from local fixture files with no separate server process to start, but the fixture files themselves accumulate in the repository over time and must be scoped per test (not shared globally) so one test's replayed interaction cannot be consumed or exhausted by another test running in parallel.
- A fourth point on the spectrum, worth naming: spinning up a real but disposable instance of the dependency (a throwaway container running the actual service, or a sandboxed real instance) trades away some speed and isolation for the highest possible fidelity, and is most appropriate when the dependency is your own team's service rather than a genuine third party.
Deciding it's safe to rely on one of these instead of the real dependency comes down to how the fidelity gap is monitored: pairing whichever technique you choose with periodic revalidation against the real service (a scheduled job that diffs the contract, or an occasional smoke test against the real dependency) is what actually keeps any of the three honest over time.
Worked example
A team virtualizing a shipping-rates API starts with hand-written stubs for speed, then migrates to a WireMock server generated from the provider's published OpenAPI spec once the hand-written stubs drift and cause a production incident (the real API added a required field the stub never returned). They still keep one recorded-and-replayed interaction from a real sandbox call specifically to catch response-shape drift the OpenAPI spec itself might miss (an undocumented field the provider actually sends), and schedule a monthly job that re-records it and diffs against the version checked into source control.
Trade-offs and pitfalls
Startup cost matters in CI: an in-process mock or stub is essentially free to instantiate per test, while a standalone mock server has real startup latency and, if shared across parallel test workers, needs per-test isolation (a unique port, a request-scoped state key) to avoid cross-test interference. UI/e2e tests calling out to a virtualized dependency have their own practical concerns, realistic response shapes, managing test data and auth tokens the mock needs to accept, and keeping the mock layer updated as the real API evolves are ongoing work, not a one-time setup cost. Isolating tests from a genuinely flaky downstream dependency is itself a valid motivating reason to reach for any of these three, on top of the pure speed argument.
Implement a small Node.js mock server that returns a configurable response for GET /users/:id. Test code should be able to set the response payload and status for a given id at runtime through a control endpoint, and reset it between tests. Outline the code and explain how a test would use this server.
Sample Answer
Direct answer
Build a small Express server that keeps an in-memory map of configured per-id responses, exposes a control endpoint to set (and another to clear) that configuration at runtime, and serves whatever was last configured for a given id on GET /users/:id, returning a clear "not configured" response otherwise.
Structured elaboration
const express = require('express');
function createMockUserServer() {
const app = express();
app.use(express.json());
const responses = new Map();
app.get('/users/:id', (req, res) => {
const configured = responses.get(req.params.id);
if (!configured) {
return res.status(404).json({ error: 'no mock configured for this id' });
}
res.status(configured.status).json(configured.body);
});
app.post('/__mocks', (req, res) => {
const { id, status, body } = req.body;
if (!id || !status) {
return res.status(400).json({ error: 'id and status are required' });
}
responses.set(id, { status, body: body ?? {} });
res.status(201).json({ ok: true });
});
app.delete('/__mocks/:id', (req, res) => {
responses.delete(req.params.id);
res.status(204).end();
});
return app;
}
module.exports = { createMockUserServer };
Test code using supertest (executed):
const request = require('supertest');
const { createMockUserServer } = require('./mock-server');
function assertEqual(actual, expected, msg) {
if (actual !== expected) {
throw new Error(`FAIL: ${msg} (expected ${expected}, got ${actual})`);
}
}
async function main() {
const app = createMockUserServer();
let res = await request(app).get('/users/1');
assertEqual(res.status, 404, 'unconfigured id should 404');
res = await request(app).post('/__mocks').send({ id: '1', status: 200, body: { id: '1', name: 'Ada' } });
assertEqual(res.status, 201, 'configuring a mock should return 201');
res = await request(app).get('/users/1');
assertEqual(res.status, 200, 'configured id should return the configured status');
assertEqual(res.body.name, 'Ada', 'configured id should return the configured body');
await request(app).post('/__mocks').send({ id: '2', status: 503, body: { error: 'unavailable' } });
res = await request(app).get('/users/2');
assertEqual(res.status, 503, 'configured error status should be honored');
res = await request(app).delete('/__mocks/1');
assertEqual(res.status, 204, 'reset should return 204');
res = await request(app).get('/users/1');
assertEqual(res.status, 404, 'reset id should 404 again');
console.log('ALL 7 ASSERTIONS PASSED');
}
main().catch((e) => { console.error(e); process.exit(1); });
Executed with node: ALL 7 ASSERTIONS PASSED (the earlier draft referenced an assertEqual helper without defining it and never invoked main(), so it silently produced no output at all; this version defines the helper, calls main(), and the real count of assertions actually made is 7, not 5).
Worked example
A UI test that needs GET /users/42 to return a specific plan tier first calls POST /__mocks with { id: "42", status: 200, body: { id: "42", plan: "pro" } }, then exercises the page under test, then (in teardown) calls DELETE /__mocks/42 so the next test starts from a clean, unconfigured state rather than inheriting whatever the previous test left behind.
Trade-offs and pitfalls
The in-memory Map means all configured mocks are shared across whatever tests are running against this one server instance; if tests run in parallel against a single shared server process, they need distinct ids or their own server instance per test, otherwise one test's configured response can leak into another's assertions, the exact interference test isolation is meant to prevent. Explicitly resetting configured mocks between tests (or spinning up a fresh server per test) avoids this at the cost of some setup overhead per test.
Unlock Full Question Bank
Get access to all 10 Mocking, Stubbing, and Test Isolation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.