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.
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.
You need to test payment flows that must validate idempotency and retry behavior, but you cannot call the production payment gateway from automated tests. Propose a strategy to mock or virtualize the gateway that preserves realistic behavior, including stateful idempotency tokens, duplicate-request detection, and injected errors. How would you verify that your mock is actually correct?
Sample Answer
Direct answer
Mock or virtualize the payment gateway with a stateful fake that tracks idempotency tokens and duplicate requests the same way the real gateway would, inject configurable error responses to exercise failure handling, and verify the mock's correctness by periodically checking its behavior against the real gateway's documented (or sandboxed) semantics rather than trusting it was built right once and never revisited.
Structured elaboration
- Stateful idempotency tokens: the fake gateway must remember which idempotency keys it has already seen, and return the SAME response for a repeated key rather than processing the charge twice, exactly mirroring how a real payment provider's idempotency guarantee works. A stateless fake that just always "succeeds" cannot exercise this at all.
- Duplicate-request detection: beyond idempotency keys, the fake should be able to detect and reject a genuinely duplicate charge attempt (same amount, same customer, in a short window) if that's part of what your production code is meant to guard against, so tests can verify your code's OWN duplicate-detection logic and not just the gateway's.
- Injected errors: the fake needs configurable failure modes (a decline, a timeout, a rate-limit response) that tests can select per-scenario, so retry logic, user-facing error handling, and reconciliation logic all get real test coverage.
- Verifying the mock is correct: this is the hardest and most often-skipped part. Options include periodically running the same test suite against the real gateway's sandbox environment and diffing behavior, keeping the fake's logic reviewed against the provider's published API documentation whenever it changes, or building the fake from the provider's official sandbox responses (a form of contract-based generation) rather than from memory of how it's supposed to work.
Worked example
A FakePaymentGateway stores a dictionary of idempotency_key -> response and, when charge(amount, idempotency_key) is called with a key already in the dictionary, returns the stored response unchanged instead of creating a new charge. A test configures the fake to return a "declined" response for a specific key, calls the order-processing code, and asserts the order is marked as payment_failed and never marked paid. A second test calls charge twice with the SAME idempotency key and amount, and asserts only one charge was recorded internally by the fake, proving the order code (or the fake itself, whichever owns the idempotency contract in this design) doesn't double-charge on a retried request.
Trade-offs and pitfalls
A fake payment gateway that only ever returns success teaches the team nothing about how the system behaves under decline, timeout, or duplicate-request conditions, exactly the conditions that matter most for a payment flow's correctness and are hardest to safely reproduce against a real gateway. The single biggest risk with any hand-built fake of a payment provider is confidence without verification, a fake that has silently drifted from the real gateway's actual idempotency window or error-response shape can make a whole suite pass while a real regression ships, so revisiting the fake against the provider's real documented behavior on a schedule, not just at initial build time, is part of the design.
Explain the roles of unit, integration, and end-to-end tests in a delivery pipeline. For each layer, describe what should typically be mocked versus run against a real dependency, and walk through a concrete example for a payment flow showing where mocks belong and why.
Sample Answer
Direct answer
As a rough default: unit tests mock everything outside the function or class under test; integration tests run against real (or lightly virtualized) adjacent components but still mock the furthest-out third parties; end-to-end tests run against real dependencies wherever it's safe and affordable to do so.
Structured elaboration
- Unit tests: the fastest, most numerous layer. Everything the unit under test calls, database, network, other services, gets mocked, so the test isolates and exercises only the logic in that one unit.
- Integration tests: verify that two or more of YOUR OWN components wire together correctly (your service and your database, your service and an internal message queue). Real (or a very high-fidelity fake of) your own infrastructure is used here, but external third parties are usually still mocked or virtualized, since the point is validating your own integration code, not the third party's uptime.
- End-to-end tests: exercise a full user-facing flow across real systems. Real external dependencies are used where safe (sandboxed accounts, staging environments); anything unsafe, costly, or nondeterministic to call for real (an actual bank transfer, an actual SMS bill) still gets stubbed even at this layer.
Worked example
For a payment flow: at the unit level, mock the PaymentGateway interface entirely and test that the order service calls charge() with the right amount and handles a thrown exception by not saving the order. At the integration level, run the order service against a real local database to confirm the SQL actually persists correctly, while still mocking the payment gateway (a third party, out of scope for this layer). At the end-to-end level, run the full checkout flow against the payment gateway's real sandbox environment, so the test confirms the actual network contract and response shapes match what your code expects, without charging a real card.
Trade-offs and pitfalls
The three-layer split breaks down if a team pushes everything into unit tests with mocks and skips the integration layer entirely: unit tests can all pass while the wiring between your own components is broken, because no test ever exercised your actual database or actual message-queue configuration. Conversely, pushing too much into end-to-end tests makes the suite slow and flaky without necessarily catching bugs any earlier or more precisely than a well-placed integration test would.
Your team's multi-tenant test suite is riddled with flaky, order-dependent failures because tests leave behind data that later tests accidentally collide with or depend on. Design a fixture and isolation strategy that fixes this for good, and explain when you would reach for a mock or a virtualized dependency instead of a full end-to-end call as part of that design.
Sample Answer
Direct answer
Designing test fixtures for isolation means each test creates and tears down exactly the state it needs through the same mechanisms production code would use (an API call, a transaction, a scoped tenant) rather than sharing ambient state, so tests can run in any order, in parallel, and be re-run safely.
Structured elaboration
- API-driven setup/teardown: create fixture data through the system's own API rather than inserting rows directly, so the fixture stays valid as the schema evolves and exercises the same code path production traffic would use.
- Database transactions and rollback: wrap each test in a transaction that starts fresh and rolls back at teardown, so no test's writes are visible to any other test, without needing to manually clean up every row.
- Tenant isolation: in a multi-tenant system, give each test its own tenant id (or a dedicated test tenant reserved for automated tests) so tests can't accidentally read or corrupt another tenant's data, and so tenant-scoped queries in the code under test are exercised correctly.
- Idempotent tests: design fixtures so re-running the same test twice in a row (after a failure, or in a retry) produces the same result rather than a duplicate-key error or an inconsistent state, typically by generating fresh unique identifiers per run instead of hardcoding them.
- Mocks and virtualization versus a full end-to-end call: prefer a mock or virtualized dependency when the fixture would otherwise need to reach outside the system under test (a third-party API, another team's service) purely to get into the right starting state; reserve full end-to-end calls for the smaller set of tests specifically validating that integration.
Worked example
A multi-tenant SaaS billing test suite gives each test function its own freshly generated tenant id and wraps all database writes in a transaction scoped to that test. A test verifying "an overdue invoice triggers a dunning email" creates its invoice through the billing API (not a raw INSERT), uses a mocked email-sending client so no real email goes out, and rolls back its transaction at teardown. Because the tenant id and the transaction are both unique per test run, the test is safe to run in parallel with a hundred other tests and safe to re-run after a failure without manual cleanup.
Trade-offs and pitfalls
Transactions alone don't isolate everything: code that reads global caches, writes to the filesystem, or calls out to a real external service bypasses the transaction boundary entirely, so those paths still need their own isolation strategy (usually mocking). A fixture design that looks isolated on paper but relies on a shared singleton cache or a shared test tenant "just this once" reintroduces the exact interference the rest of the design was built to prevent.
Unlock Full Question Bank
Get access to all 34 Mocking, Stubbing, and Test Isolation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.