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.
Discuss lifecycle management for test doubles in a large test suite: how they get created and configured, how you verify they were used correctly, and how they get reset and torn down between tests. Propose naming and fixture-scope conventions to avoid leaking mock state between tests and keep mocks consistent across a team.
Sample Answer
Direct answer
Manage a test double's lifecycle explicitly: create and configure it per test (or per fixture scope), verify it was used as expected during the test, and reset or tear it down afterward so no leftover configuration or recorded state leaks into the next test, especially under parallel execution.
Structured elaboration
A leftover mock is a concrete, common failure mode: if test A configures a mock to always return a specific value and the test framework reuses the same mock instance for test B without resetting it, test B can silently pass or fail based on test A's leftover configuration rather than its own setup, exactly the kind of order-dependence test isolation is meant to prevent, and it gets worse when tests run in parallel and two tests race to configure the same shared mock at once.
Conventions that keep this manageable at scale:
- Naming conventions: consistent naming for mock variables and their setup helpers so it's obvious, reading a test, which mocks exist and what they're configured to do.
- Fixture scope: most testing frameworks let you declare whether a fixture (including a mock) is created fresh per test, per test class, or per test session; default to per-test scope for mocks unless there's a clear, deliberate reason (like an expensive-to-construct fake) to share one, and if you do share one, reset it explicitly between tests.
- Reset semantics: use the mocking framework's built-in reset capability (clearing recorded calls and configured return values) rather than manually reconstructing state, so resets stay consistent as the suite grows.
- Verification: check a test double was used correctly with the mocking framework's own interaction-verification API rather than inspecting internal state by hand, assert on exact call counts and arguments (
mock.assert_called_once_with(...),verify(mock).method(args)), assert on calls that must NOT have happened (assert_not_called,verify(mock, never())), and, when call order is itself a real requirement, assert it explicitly (InOrder/assert_has_callswithany_order=False) rather than only checking the final return value.
Worked example
A test suite that shares one mock EmailClient instance across all tests in a file (for speed) must call the framework's reset function in a setUp/beforeEach hook, clearing both the configured return values and the recorded call history, so a later test asserting "send was called exactly once" isn't accidentally counting a call made by an earlier test that reused the same mock instance without resetting it.
Trade-offs and pitfalls
Sharing a mock instance across tests for speed trades away some safety: it's faster to construct once, but every test now depends on the reset logic being complete and correctly wired into the test lifecycle, and a single missed reset can produce confusing, hard-to-reproduce failures that only show up depending on test execution order. Under parallel test execution, sharing isn't safe at all unless the mock (and its reset) is somehow made thread-safe or each parallel worker gets its own instance; the simplest and most robust default is a fresh mock per test.
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.
Explain the differences between mocks, stubs, fakes, spies, and dummies. For each kind of test double, give a concrete example from a typical web application (an HTTP API call, a database, a message queue, or a cache) and a short guideline for when you would prefer that double over the others.
Sample Answer
Direct answer
A test double is a stand-in for a real dependency in a test. The five common kinds differ in what they do when called and what the test asserts about them: a dummy is passed around but never actually used, a stub returns canned data, a fake is a working but simplified implementation, a mock records calls so the test can verify they happened correctly, and a spy wraps a real object while also recording calls to it.
Structured elaboration
| Double | Behavior when called | What the test checks | Typical web-app example |
|---|---|---|---|
| Dummy | Does nothing meaningful; only fills a required parameter slot | Nothing about it directly | Passing a placeholder database-connection object into a constructor that requires one but is never queried on the code path under test |
| Stub | Returns a pre-programmed value | The return value the code under test produces | Making a "get exchange rate" HTTP client return a fixed 1.08 so a pricing calculation is deterministic |
| Fake | Runs real logic, just a lighter-weight implementation | The behavior/output, same as against the real thing | An in-memory key-value store used instead of a real Redis instance |
| Mock | Returns canned data AND records how it was called | That specific calls happened, with specific arguments, in the right order | Verifying that PaymentGateway.charge() was called exactly once with the correct amount |
| Spy | Wraps a real object, forwards calls through, and records them | Both real behavior and the interaction | Wrapping a real email-sending service so you can assert "send was called" while letting a test double catch the actual network call underneath |
The line between stub and mock is really about what the test asserts on: a stub only shapes the INPUT to the code under test (state verification), while a mock is used to verify OUTPUT in terms of interactions (behavior verification). The same test-double library (Mockito, unittest.mock, Sinon) is usually used to build all five; the taxonomy names roles, not library features.
Worked example
For a database example: a stub database client always returns a fixed list of three users for find_active_users(), regardless of what was inserted, so a report-generation test has predictable input. A mock database client would instead be used to verify that save(user) was called exactly once with a User object whose status field is "active", when testing the code that is supposed to activate a user. A fake database would be a real, lightweight in-memory dictionary-backed store that actually persists and retrieves records within the test, useful when the test needs realistic query behavior (like "insert then find") that a stub's fixed answer can't provide.
Trade-offs and pitfalls
Reach for a dummy when a dependency is only required to satisfy a constructor or function signature and is never actually exercised on the path under test; building anything more elaborate (a stub, a fake) for it would be wasted setup effort. Reach for a stub when you need to control an input; reach for a mock when the ACT of calling the dependency (with the right arguments, in the right order) is itself part of the behavior being tested, such as making sure a payment is charged exactly once. Reach for a spy when you want the dependency's real behavior to genuinely happen (unlike a mock, which fully replaces it) while still asserting that a specific interaction occurred, such as confirming a real cache was actually written to while also checking the write call's arguments. Overusing mocks where a stub would do makes tests brittle: every internal refactor that doesn't change observable behavior can still break a mock-heavy test, because the test is coupled to how the code calls its dependency rather than what the code produces.
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.
Explain how threads, async/await, and separate processes each affect test isolation, resource usage, and the risk of nondeterministic behavior in a test runner. What would you recommend for designing a parallel test runner that avoids shared-state issues and memory leaks, including how you would scope fixtures and decide which tests are safe to parallelize versus which need to stay serial?
Sample Answer
Direct answer
Threads, async/await, and separate processes each threaten test isolation in a different way: threads share memory directly and can race on any shared mutable state, async/await tasks share memory too but only yield at explicit await points (making races narrower but still real), and separate processes don't share memory at all but can still interfere through shared external resources like a database or a port.
Structured elaboration
- Threads: the highest interference risk, since any shared mutable object can be read and written from multiple threads at truly arbitrary points, including partway through a non-atomic operation. A parallel test runner using threads needs each test's data either fully isolated (no shared objects) or protected by synchronization, and must watch for memory leaks from threads that outlive the test that spawned them.
- Async/await (single-threaded concurrency): interleaving only happens at
awaitpoints, since code between awaits runs to completion without preemption, which narrows the surface for races but doesn't eliminate it, two async tasks can still race on a shared variable if one awaits in the middle of a read-modify-write sequence the other also touches. - Separate processes: memory isn't shared at all, which removes in-memory races entirely, but tests running in separate processes can still interfere through anything they share externally, the same database, the same listening port, the same temp directory, or the same external service account.
Designing a parallel test runner that avoids shared-state issues: give each test (or each parallel worker) its own isolated resources wherever possible, an in-memory or per-worker database, dynamically-assigned ports instead of hardcoded ones, per-worker temp directories, and be deliberate about fixture scope so an expensive-to-create resource that IS shared across tests in a worker is either read-only or explicitly protected.
Deciding which tests are safe to parallelize: a test is safe to run in parallel with others if it doesn't depend on or mutate anything the other parallel tests can observe, tests touching genuinely exclusive external resources (a fixed port, a singleton external sandbox account) should stay serial or get resource-level locking rather than being forced into parallel execution.
Worked example
A parallel test runner using worker processes (not threads) for isolation still saw intermittent failures because two workers both tried to bind port 5000 for a local test server; the fix was to have each worker request an OS-assigned ephemeral port instead of hardcoding one, removing the shared external resource that had been silently coupling otherwise fully isolated processes.
Trade-offs and pitfalls
Choosing process-based parallelism over thread-based parallelism trades away in-memory races for higher per-worker overhead (each process needs its own runtime and memory), it's a legitimate trade for many test suites but not free. A parallel runner design that assumes "no shared memory" automatically means "no interference" misses the port/database/file-based interference case entirely, which is exactly the kind of gap that produces intermittent, hard-to-reproduce parallel-test failures.
Unlock Full Question Bank
Get access to all 16 Mocking, Stubbing, and Test Isolation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.