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.
Explain approaches to intercept and modify network requests and responses during a Selenium test in order to simulate backend conditions. Compare using an HTTP proxy, browser-level network interception, and a service-virtualization tool, and provide a short example showing how you would stub a single JSON API response.
Sample Answer
Direct answer
Three approaches intercept network traffic during a Selenium test at different layers: an HTTP proxy sits between the browser and the network and can rewrite any request/response; browser-level network interception (via the Chrome DevTools Protocol) hooks directly into the browser's own network stack; and a service-virtualization tool replaces the backend entirely with a configurable fake server the browser talks to normally.
Structured elaboration
| Approach | How it works | Pros | Cons |
|---|---|---|---|
| HTTP proxy (e.g. a local proxy the browser is configured to route through) | Sits outside the browser, intercepts and can rewrite any request/response crossing it | Works across any browser or client, language-agnostic | Extra process to run and configure, and HTTPS interception needs a trusted certificate installed in the browser |
| Browser-level interception via the Chrome DevTools Protocol | The test driver registers request/response handlers directly with the browser's own devtools connection | No separate process, no certificate trust issues, very precise control per-request | Chromium-specific (or needs an equivalent for other engines), and ties the test to the devtools API surface |
| Service virtualization | The backend the app calls is a real, separately configurable server | Exercises the app's real network code path against a realistic backend, reusable across UI and API tests | Slower to set up, requires the app to be pointed at the virtual server's URL instead of production |
A short example stubbing a single JSON API response (shown here with an HTTP-level interception library so it is genuinely runnable without a browser; the identical idea applies whether the interception happens via a proxy or the Chrome DevTools Protocol):
import responses
import requests
def fetch_profile(user_id):
resp = requests.get(f"https://app.example.com/api/profile/{user_id}")
resp.raise_for_status()
return resp.json()
@responses.activate
def test_stub_a_single_json_api_response():
responses.add(
responses.GET,
"https://app.example.com/api/profile/77",
json={"id": 77, "plan": "pro"},
status=200,
)
result = fetch_profile(77)
assert result == {"id": 77, "plan": "pro"}
assert len(responses.calls) == 1
Executed with pytest:
test_s13_network_interception.py::test_stub_a_single_json_api_response PASSED
1 passed in 0.03s
Worked example
Testing a profile page that should show a "Pro" badge only for pro-tier users: stub the GET /api/profile/77 call to return {"plan": "pro"} and assert the badge renders; stub the same endpoint to return {"plan": "free"} in a second test and assert the badge does not render. Neither test depends on a real backend being up, and both are deterministic regardless of what the real profile service currently returns for user 77.
Trade-offs and pitfalls
An HTTP proxy adds a genuinely separate moving part (the proxy process itself, HTTPS certificate trust) to the test environment; browser-level interception avoids that but is coupled to whichever browser engine's devtools protocol you're using; service virtualization is the heaviest but also the most representative of real end-to-end behavior. Whichever layer is chosen, the stubbed response shape needs to be kept realistic, if the real API adds a required field the stub never includes, the UI test can pass while the real integration is actually broken.
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.
In Python, you have a function fetch_user(user_id) that calls requests.get(...) against a live API and returns parsed JSON. Write a unit test using unittest and unittest.mock that stubs the call so the test runs entirely offline, and assert both the returned data and that the call was made with the expected URL.
Sample Answer
Direct answer
Patch requests.get for the duration of the test with unittest.mock.patch, configure the mock's return value to look like a real Response object, and assert both the parsed return value and the exact call arguments so the test proves the function calls the right URL, not just that it returns something.
Structured elaboration
from unittest.mock import patch, MagicMock
import requests
def fetch_user(user_id):
response = requests.get(f"https://api.example.com/users/{user_id}")
return response.json()
import unittest
class FetchUserTest(unittest.TestCase):
@patch("requests.get")
def test_fetch_user_returns_parsed_json_and_calls_expected_url(self, mock_get):
mock_response = MagicMock()
mock_response.json.return_value = {"id": 42, "name": "Ada Lovelace"}
mock_get.return_value = mock_response
result = fetch_user(42)
self.assertEqual(result, {"id": 42, "name": "Ada Lovelace"})
mock_get.assert_called_once_with("https://api.example.com/users/42")
Executed with pytest:
py-sandbox/test_s17_fetch_user.py::FetchUserTest::test_fetch_user_returns_parsed_json_and_calls_expected_url PASSED
1 passed in 0.01s
@patch("requests.get") patches the attribute directly on the real requests module object, which is the correct target here because fetch_user calls requests.get(...) by looking up get on the requests module at call time; since there is only one requests module object in the process, patching its get attribute affects every caller, regardless of which file imported requests.
Worked example
Without assert_called_once_with, a bug where fetch_user accidentally hit .../users/{user_id}/profile or forgot to URL-encode the id would still pass a test that only checks the returned data (since the mock returns the same canned JSON no matter what URL it's called with). Asserting on the exact call arguments is what actually proves the function constructs the right request, not just that it can parse a response.
Trade-offs and pitfalls
A common mistake is patching the WRONG target, @patch("some_module_where_requests_is_imported.requests.get") only works if that's genuinely how the lookup resolves; when the code does import requests and then calls requests.get(...), patching the module attribute directly ("requests.get") is correct and more robust to refactors than patching a re-exported name. This test also completely bypasses whatever the real API would do, which is the point for a fast unit test, but it means it teaches nothing about whether https://api.example.com is even reachable or returns the shape assumed here; that's a job for a smaller number of higher-fidelity tests, not this one.
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.
Write a pytest unit test for a Python function schedule_next_run(last_run_timestamp) that returns the next UTC timestamp exactly 24 hours later. Use a time-freezing tool or monkeypatching to control system time so the test is deterministic, and include a test case that covers a daylight-saving-time boundary.
Sample Answer
Direct answer
Use freeze_time to pin the clock the function reads, so schedule_next_run is exercised at a known instant, then assert on the exact returned timestamp, including one test case that straddles a daylight-saving-time boundary.
Structured elaboration
The function under test operates purely on a UTC timestamp, so a correct implementation should be immune to local daylight-saving shifts entirely; the DST test case exists specifically to catch an incorrect implementation that accidentally reasons in local time or re-derives "now" from a local-time source partway through.
from datetime import datetime, timedelta, timezone
from freezegun import freeze_time
def schedule_next_run(last_run_timestamp: datetime) -> datetime:
"""Return the next run time exactly 24 hours after last_run_timestamp, in UTC."""
return last_run_timestamp + timedelta(hours=24)
@freeze_time("2026-06-15 10:00:00", tz_offset=0) # an ordinary day, nowhere near a DST transition
def test_schedule_next_run_normal_day():
now = datetime.now(timezone.utc)
result = schedule_next_run(now)
expected = datetime(2026, 6, 16, 10, 0, 0, tzinfo=timezone.utc)
assert result == expected
@freeze_time("2026-03-08 10:00:00", tz_offset=0)
def test_schedule_next_run_dst_boundary_us_spring_forward():
# US DST spring-forward happened 2026-03-08 (2am -> 3am local, US Eastern).
# Because schedule_next_run operates purely in UTC, the +24h arithmetic
# must NOT shift by the local wall-clock DST jump.
now = datetime.now(timezone.utc)
result = schedule_next_run(now)
expected = datetime(2026, 3, 9, 10, 0, 0, tzinfo=timezone.utc)
assert result == expected
assert (result - now) == timedelta(hours=24)
Executed with pytest:
py-sandbox/test_s9_schedule.py::test_schedule_next_run_normal_day PASSED
py-sandbox/test_s9_schedule.py::test_schedule_next_run_dst_boundary_us_spring_forward PASSED
2 passed in 0.08s
Worked example
The DST test freezes the clock exactly on the date of a real US spring-forward transition. If schedule_next_run were buggy and internally converted to local time, added "1 day" in local wall-clock terms, and converted back (a plausible mistake when a developer reaches for a naive local-time date + 1 day library call instead of UTC-timestamp arithmetic), the result would land 23 real hours later instead of 24, because one hour of local wall-clock time disappeared that day. The test's explicit (result - now) == timedelta(hours=24) assertion is what would catch that specific class of bug; the equality check on the expected UTC datetime alone would also catch it, but the explicit duration assertion makes the DST-specific intent of the test unambiguous to a future reader.
Trade-offs and pitfalls
freeze_time patches the standard library's time functions for the duration of the decorated test; if the code under test reads time through some other mechanism (a compiled extension, a separate process, a raw system call not covered by the patch), it won't be affected and the test will silently exercise the real clock instead. Always verify that a freeze-time test actually pins the value you expect by asserting on a specific timestamp, as done here, rather than only checking a relative delta, since a relative-only assertion can accidentally pass even if the freeze didn't take effect.
Unlock Full Question Bank
Get access to all 17 Mocking, Stubbing, and Test Isolation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.