Unit Testing Interview Questions for Backend Engineers: Isolation, Test Doubles, and Useful Assertions
Quick Overview
Compare practical test doubles and assertions for expiry, timeout, and persistence in a quote operation.
A unit test for a quote service fails after someone changes a price lookup from two calls to one. Customers receive exactly the same quote and no extra messages. Another test goes green even when the service charges the wrong amount, because its mocked calculator returns the number the test expects. In a backend unit testing interview, define which behavior you own, choose the smallest double that exposes it, and assert the result a caller or downstream system can observe.
This exercise uses a fictional quote service written in Python. The same seams apply in other languages. The Python unittest.mock documentation covers test-double primitives and call assertions, and the pytest fixture guide covers fixture scope and reuse. When you need real database behavior, compare the tradeoffs with PracHub’s Testcontainers interview exercise.

What counts as the unit for a backend service?
The quote operation takes a product SKU, a request ID, and an explicitly supplied time. It reads the price and valid-through time from a catalog dependency. If the catalog is unavailable, the caller gets a retryable result, and no quote is saved. If the price has expired, the result is unavailable for that SKU, and again no quote is saved. A valid price produces a quote with the price in integer cents, the requested SKU, and the request ID. The repository persists it and returns the reference.
At this boundary, the quote operation owns the cutoff decision and the choice to persist a record. A test can include the real policy and a controlled catalog and repository without reaching the network. The unit boundary is the decision you want to hold stable. If calculating eligible prices is its own pure function, test it directly with arbitrary prices and timestamps. A service test should still show that it translates that function’s return into an appropriate effect.
The interviewer may ask which values are independent. The expected price comes from the stated input and rule, so it belongs in the test fixture rather than a call to the same calculation as the subject. The request ID should be distinct from the SKU. A swapped argument should fail the test, even if both have string type. Give the repository reference a different form so a return-value test would catch the wrong identifier. Choose time near an explicit cutoff rather than using the wall clock.
Which doubles let you assert the actual behavior?
Use a stub for a controlled answer, a fake when a local implementation can preserve the relevant state, and a spy or mock when the interaction is the effect you need to prove. In Python, the same Mock object can support more than one of those roles. Name the role by what the test does with it. That is more precise than classifying everything that is not a production object as a mock.
| Boundary | Suggested double | Assertion that carries evidence |
|---|---|---|
| Clock | Pass an aware datetime or supply a controllable clock | Cutoff behavior at the exact expiry |
| Catalog successful lookup | Stub returning a known price and expiry | Quote contains correct SKU and price at calculation time |
| Catalog times out | Stub or mock with a TimeoutError side effect | Retryable outcome and no saved record |
| Quote store | In-memory recording fake | Saved row contains request ID, price, and SKU |
| Message publication when introduced later | Spy for a contractually meaningful effect | An eligible update carries the expected quote ID, with documented multiplicity |
One caveat about the storage fake matters in interviews. It can exercise service choices, but it cannot prove that a database unique constraint prevents a real race. Use a real database for the duplicate-request and concurrent insert contract if the feature promises it. The same limitation applies to a mock that throws the exact exception you anticipate. It tests translation in the service, while a separate adapter test verifies what the SDK throws in that setup.

What would the first two tests look like?
Here is a small excerpt. Substitute your service API and keep both successful and failed paths. The practice rule treats a quote as eligible only while the current time is strictly before expiry.
from datetime import datetime, timezone
from unittest.mock import create_autospec
expiry = datetime(2026, 11, 16, 15, 0, tzinfo=timezone.utc)
def test_quote_persists_the_price_before_cutoff():
catalog = create_autospec(Catalog, instance=True, spec_set=True)
catalog.lookup.return_value = Price(cents=2499, expires_at=expiry)
store = RecordingQuoteStore()
result = QuoteService(catalog, store).quote(
sku="BAG-4",
request_id="req-802",
now=expiry.replace(minute=59, hour=14),
)
assert result.status == "quoted"
assert result.reference == "quote-1"
assert store.saved == [Quote("req-802", "BAG-4", 2499)]
def test_catalog_timeout_leaves_no_quote():
catalog = create_autospec(Catalog, instance=True, spec_set=True)
catalog.lookup.side_effect = TimeoutError
store = RecordingQuoteStore()
result = QuoteService(catalog, store).quote(
sku="BAG-4", request_id="req-802", now=expiry,
)
assert result.status == "retryable"
assert store.saved == []
The example assumes a local RecordingQuoteStore saves data and consistently issues the first fake reference. Add a separate test with a successful catalog read at exactly expiry. The timeout case and the expiry case cannot demonstrate each other. Time out before the service has a usable price, and choose the status defined for an expired price only once it received the catalog response. A single test that sets both conditions and checks only “no quote” would miss an incorrect error classification.
The Python documentation describes how autospeccing lets a mock conform to an object’s signature. It can expose some changes that a free-form mock would accept. It cannot establish field semantics or return contracts across processes. If asked why the successful test does not count calls to lookup, say whether the number is a public requirement. When direct catalog billing or a retry budget makes it observable and important, add a test specifically for that budget.
How would you improve a weak set of assertions?
Given an existing suite, pay attention to tests that pass when behavior is visibly wrong. Imagine replacing the stored price with a constant 2,499. The first test above would still pass. A second valid quote with a different price and SKU would catch the defect, and a fixture where a zero amount is allowed can reveal a mistaken truthiness check. When currency is a product rule, keep the currency as a separate dimension. A test expected value of 2499 cannot establish whether the quote came from dollars, euros, or cents before rounding.
Look for tests that assert the service’s private choreography. A test that verifies lookup, normalization, persistence, and formatting in call order is sensitive to refactoring. Save order belongs in a test when it represents a defined business effect, such as emitting a receipt only after a successful commit. Assert the downstream boundary produces zero receipts when the save fails and the expected one after it succeeds. Prove transaction behavior with the backend that owns the commit.
Use errors with different consequences. A transient lookup timeout may permit a retry, a malformed catalog record may need a different error, and a storage failure after computing a quote could require the caller to receive no success reference. Write tests so that deleting the exception class or broadening it changes at least one known outcome. This is why an “any exception” assertion is rarely helpful. Scope assertion text to the part callers depend on; free-form error text can change without changing the contract.
How much should fixtures hide?
A business parameter that drives the answer should be visible in the test that depends on it. In the quote suite, expiry and price are visible, but the utility that creates a catalog autospec can be shared. Keep per-test state isolated by default. A mutable fake that is shared across tests can turn an order-dependent failure into wasted debugging time. The unittest documentation provides additional context on setup, tear-down, and test organization. Use framework conveniences to clarify the case being tested.
An interviewer might point to a suite that becomes slow after adding 200 service tests. Measure first. If every unit test starts a database container, move pure policy decisions and orchestration checks to local fixtures. Preserve a smaller integration suite for database semantics. For asynchronous code, wait on a controlled signal or use a deterministic scheduler where supported. Sleeping for a business interval adds time and can still miss the event if the machine is slow.
Finish by explaining which tests would have changed after the production bug. If the service emitted duplicate receipts on retry, add a failing case against the exact published behavior and describe the test against real persistence where concurrent retry is possible. If the discovered symptom was merely a lookup move with equal observable behavior, remove the overly specific call-count assertion unless a documented budget needs it.
How would you test a retry budget without hiding the service logic?
Suppose a product owner adds a rule that a quote operation may retry a timed-out catalog call once. Program the stub to raise TimeoutError on its first call and return the price on its second. Assert a single saved quote with the expected reference and verify the catalog was called twice. Add a second test where both calls time out and verify the retryable result, an empty store, and the same two-call budget. Finally add a malformed price response and verify the chosen permanent error without a retry. These cases protect observable load as well as the price.
A tempting fixture is to have the fake repository return success without tracking data. If the service accidentally saves a quote from the first attempt as well, the returned reference can look correct. Use a recording fake and compare the full list. Then mutate the fake catalog to supply a real delay only in an integration rehearsal with a controlled clock or scheduler. The unit suite exercises the decision deterministically. The integration check establishes that the deployed adapter’s cancellation and timeout behavior conforms.
In a review, point to exactly where each expected value comes from. The two attempts are a product rule, the stored amount comes from a distinct price fixture, and the empty store means the caller will have no quote to discover later. If the requirement changes from two attempts to three, update the deliberate budget cases and preserve price, currency, and persistence expectations.
When a teammate asks to move the mock inside the implementation, ask how the test will represent a catalog timeout without knowing the new private function. Supplying the collaborator at construction preserves a stable call surface. An adapter-level fixture can then confirm the adapter implements that surface with approved input. If the service accepts several currencies, add separate successful fixtures before checking that normalization and arithmetic can vary independently.
Related PracHub interview practice
Use these five questions to rehearse the skills in the exercise. The practice set combines questions from different roles and settings.
| PracHub question | What to practise |
|---|---|
| Write Unit Tests for a Given Python Class, Covering Normal and Edge Cases | Choose cases that expose wrong behavior in a Python class. |
| Validate Unit-Test Coverage and Identify Missing Scenarios | Identify a regression invisible to the current coverage report. |
| Test-Driven Pair Programming: Grow a Java Set Class from Unit Tests | Use a meaningful assertion to drive one behavior change. |
| Exposing a Python Function as a REST Endpoint with FastAPI and Unit Testing It | Separate API adapter checks from service policy checks. |
| Design Calendar Event CRUD with Unit Tests | Decide what state belongs in an isolated backend fixture. |
Choose one policy and one adapter from the PracHub Testcontainers exercise. Practise deciding which bug each test observes, then change the implementation while keeping the result steady and explain which tests should still pass.
Comments (0)