Interview Questions: Testing Your Code
Testing questions separate candidates who can write an assert statement from candidates who understand why a test suite exists at all. This set covers unittest vs. pytest, what makes a test actually good, mocking vs. stubbing, test isolation, why 100% coverage is a trap, TDD basics, flaky tests, and the testing pyramid.
1 What's the actual difference between unittest and pytest, beyond "one is built-in"?
unittest requires subclassing TestCase and using its assertion methods (assertEqual, assertTrue, assertRaises) — verbose, but zero installs since it ships with Python. pytest lets a test be a plain function using Python's own assert statement, and rewrites failures to show exactly which values differed, without needing a specific assertion method per comparison. pytest also auto-discovers fixtures, supports plugins (coverage, parallel runs, mocking helpers), and is what the overwhelming majority of real-world Python codebases actually use day to day, even though unittest-style tests still run fine under pytest's runner.
Saying they're "basically the same thing" without being able to name a concrete difference, or claiming pytest is a completely different testing philosophy rather than a more ergonomic layer over the same core idea (arrange, act, assert).
Follow-up"Can pytest run unittest-style tests?" (Yes — pytest can discover and run TestCase-based tests too, which is part of why teams can adopt it without rewriting an existing unittest suite all at once.)
2 How does pytest know which functions in a file are tests?
Test discovery is convention-based, not configuration-based by default: pytest looks in files matching test_*.py or *_test.py, and within those files, collects any function whose name starts with test_ (and any class named Test* containing such methods). A function that doesn't match that prefix — even one full of asserts — is silently skipped and never runs as a test at all.
Assuming pytest runs every function in a file, or not realizing a misnamed test function (missing the test_ prefix) will silently never execute — no error, no warning, it just doesn't show up in the results.
"If a test function is misspelled as tset_login(), what happens when you run pytest?" (Nothing — pytest collects 0 tests for that function, no error is raised, and it's easy to mistake "0 failures" for "everything passed" when really nothing ran at all.)
3 What makes a unit test "good," beyond just having assertions in it?
A good unit test is fast, isolated (doesn't depend on other tests or shared state), deterministic (same result every run, not dependent on time/randomness/network), and tests one specific behavior so a failure immediately tells you what broke. It should also test behavior — what the function is supposed to accomplish — rather than implementation details, so that refactoring the internals without changing the outward behavior doesn't break the test for no real reason.
Red flagsEquating "good test" with "has a lot of assertions" or "high coverage number," without mentioning isolation, determinism, or speed at all.
Follow-up"Give an example of a test that asserts on implementation details instead of behavior." (Asserting that a sort function internally calls a specific helper method, rather than asserting the output list is actually sorted — the first breaks the moment someone refactors the internals, even if the sorting still works correctly.)
4 What is the AAA pattern, and why does structuring a test around it matter?
Arrange, Act, Assert: set up whatever the test needs (data, objects, mocks) in the Arrange step, perform the one action being tested in the Act step, then check the result in the Assert step. Keeping these three phases visually and logically separate — even with a blank line or comment between them — makes a test readable at a glance: anyone can tell what's being tested, what action triggers it, and what's actually being verified, without tracing through tangled setup-and-check code.
Red flagsNot being able to name the three phases, or writing/describing a test where setup, the action, and assertions are all interleaved with no clear structure.
Follow-up"Where would a mock's configuration (like return_value) go in this pattern?" (In the Arrange step — configuring what a mock should do is part of setting up the test's preconditions, before the actual action being tested runs.)
5 What's the difference between a mock and a stub?
Both are test doubles — fake stand-ins for a real dependency — but they answer different questions. A stub just returns canned data so the code under test has something to work with; the test cares about the code's resulting behavior/output, not about how the stub was used. A mock additionally records how it was called, so the test can assert on the interaction itself — that a method was called, how many times, and with what arguments (assert_called_once_with(...)). In practice, unittest.mock.Mock/MagicMock can serve as either, depending on whether the test actually checks call history or just uses the configured return value.
Using "mock" and "stub" as pure synonyms with no distinction at all, or being unable to explain what "asserting on the interaction" actually means in practice.
Follow-up"If a test only checks the function's return value and never inspects the fake object's call history, is that fake object being used as a mock or a stub?" (A stub — it's supplying canned data, but the test isn't verifying anything about how it was called.)
6 Why should a test suite avoid making real network calls, database writes, or file system changes?
Real external calls make a test suite slow (network round-trips add up fast across hundreds of tests), flaky (the network, a third-party API, or a shared database can fail for reasons that have nothing to do with whether the code under test is correct), and sometimes actively dangerous (a test that really charges a payment or really sends an email on every run is a serious liability). Mocking the external dependency keeps the test fast, deterministic, and focused only on the logic that's actually being tested.
Red flagsTreating "just run it against the real API in tests" as a reasonable default, or not recognizing the difference between a unit test (should mock externals) and an integration test (deliberately exercises real externals, on purpose, in a separate, smaller suite).
Follow-up"Is it ever correct for a test to hit a real external dependency?" (Yes — integration tests exist specifically for this, verifying the real wiring actually works. The key is that they're a deliberate, separate, typically smaller and slower category of test, not the default for every unit test.)
7 What does "test isolation" mean, and what's a concrete way tests can accidentally violate it?
Test isolation means each test's outcome depends only on itself — not on which other tests ran before it, or in what order. A common way to accidentally violate it: a shared, module-level object (a database connection, a list, a class instance) that multiple tests all mutate, instead of each test getting its own fresh instance. One test's leftover state then silently leaks into the next test that happens to run afterward, so a test can pass or fail depending purely on execution order — a bug that's hard to reproduce because running the "failing" test alone often passes fine.
Red flagsNot recognizing module-level/shared fixture state as a real risk, or assuming test order is always guaranteed to be the same and therefore "it works" is good enough justification for shared state.
Follow-up"How does a pytest fixture with the default scope help avoid this?" (A default-scoped — function-scoped — fixture reruns its setup code fresh for every single test that requests it, so each test gets its own new object instead of a shared one, which is exactly what prevents this kind of leak.)
8 What are setUp/tearDown in unittest, and how does pytest's @pytest.fixture relate to them?
setUp() runs before every test method in a TestCase, and tearDown() runs after — used to build fresh state before a test and clean up afterward (closing a file, resetting a connection). @pytest.fixture covers the same underlying need but more flexibly: a fixture function provides setup by returning a value tests can request as a parameter, and can handle teardown too, using yield instead of return — code after the yield runs as cleanup once the test finishes. Fixtures can also be scoped (function, module, session) and shared selectively, which setUp/tearDown can't do as flexibly.
Confusing setUp with something that runs once per whole test file/class (it runs once per test method, by default), or not knowing that yield is how a pytest fixture provides teardown logic.
"What does the code after a fixture's `yield` statement do?" (It runs as teardown, after the test that used the fixture finishes — whether the test passed or failed — making it the fixture equivalent of `tearDown()`.)
9 Why isn't 100% code coverage the goal of a good test suite?
Coverage measures which lines executed during the test run — it says nothing about whether the right things were actually asserted on. A test can call every line of a function and still pass with zero meaningful assertions (or a trivially wrong one, like assert True), driving coverage to 100% while verifying nothing. Coverage is a useful signal for finding code that's never exercised at all — a genuinely useful "you have a blind spot here" flag — but treating the number itself as the target incentivizes writing hollow tests just to move the metric, instead of writing tests that would actually catch a real bug.
Treating coverage percentage as a direct proxy for test quality, or not being able to describe a test that achieves high coverage while testing nothing meaningful.
Follow-up"What's coverage actually good for, then?" (Finding code paths with NO tests at all — an untested error-handling branch, an untested edge case — as a starting point for where to add real tests, not as a scorecard to maximize for its own sake.)
10 What is TDD (test-driven development), at a basic level?
A workflow where the test is written before the implementation, in a short repeating cycle: write a test for behavior that doesn't exist yet (it fails — "red," since the code doesn't exist), write just enough code to make it pass ("green"), then clean up the implementation while keeping the test passing ("refactor"). The claimed benefit is that it forces the test to actually specify the desired behavior clearly, up front, rather than being written after the fact to match whatever the code already happens to do.
Red flagsDescribing TDD as simply "writing tests" without the specific before-the-code, red-green-refactor cycle, or claiming it's the only legitimate way to write well-tested code (it's one workflow among several valid ones).
Follow-up"What's a risk of writing tests strictly after the implementation instead?" (The test can end up unconsciously matching whatever the code already does — including its bugs — rather than what the code was actually supposed to do, since there's no failing test forcing the author to state the intended behavior independently first.)
11 What's a flaky test, and what usually causes one?
A flaky test is one that passes sometimes and fails other times with no code changes in between — the exact same test, the exact same code, different outcomes across runs. Common causes: depending on real wall-clock time (a test that assumes "this runs in under 1 second" or checks against datetime.now() directly), depending on execution order via shared/leaked state between tests, depending on network calls that can time out, or depending on dictionary/set iteration order in older Python versions or non-deterministic data structures.
Suggesting "just re-run it until it passes" as an acceptable fix rather than diagnosing the actual non-determinism, or not recognizing shared fixture state as a common flaky-test cause.
Follow-up"Why is a flaky test worse than a test that just always fails?" (An always-failing test is at least honest and gets fixed immediately. A flaky test erodes trust in the whole suite over time — people start reflexively re-running failures instead of investigating them, which means a real regression can hide behind "oh, that test is just flaky" and get ignored.)
12 What is the "testing pyramid," and why does it recommend many unit tests but few end-to-end tests?
The testing pyramid is a rough guideline for how a test suite's effort should be distributed across levels: a large base of fast, isolated unit tests (testing individual functions/classes), a smaller middle layer of integration tests (testing how a few real pieces work together), and a small top layer of end-to-end tests (testing the whole system through its real interface, like a browser or a full API call chain). The shape reflects a real tradeoff: end-to-end tests give the most realistic confidence but are slow, brittle, and expensive to maintain, while unit tests are fast and pinpoint failures precisely but can't catch integration-level problems on their own — so the pyramid pushes most coverage down to the cheap, fast layer and reserves the expensive layer for what only it can verify.
Red flagsAdvocating for mostly end-to-end tests as the primary strategy ("test through the real UI/API for everything") without acknowledging the speed and maintenance cost, or not being able to name what each layer is actually good at.
Follow-up"If a bug could be caught by either a unit test or an end-to-end test, which should catch it, and why?" (The unit test, when possible — it runs faster, isolates exactly which piece of logic is broken, and doesn't require the whole system to be running, which is why the pyramid pushes as much coverage as it can down to that level.)
13 When would you deliberately choose NOT to mock something?
Mocking is for genuine external boundaries — a network call, a database, the clock, anything slow/non-deterministic/side-effecting. It's the wrong tool for a fast, pure, in-process piece of logic that's part of what's actually being tested: mocking a helper function that the code under test calls internally, purely to isolate the caller, usually means the test stops verifying that the two pieces actually work together correctly — exactly the kind of gap an integration test exists to catch. Over-mocking can also mean a test technically exercises very little real code, giving a false sense of coverage.
Red flagsTreating "mock everything the function touches" as a universal best practice, without distinguishing a genuine external dependency from ordinary internal logic that should just run for real during the test.
Follow-up"What's a concrete cost of mocking too aggressively?" (A refactor that changes how two internal pieces of your own code collaborate can pass every test — because the collaboration itself was mocked away — while the real, unmocked system is actually broken; the tests never had a chance to catch it.)
14 A candidate says "I test everything, so my code has no bugs." How would you respond?
Tests only prove the specific cases they check — they can't prove the absence of bugs in general, only the presence of correct behavior for the inputs actually exercised. A thorough suite dramatically raises confidence and catches regressions, but "no bugs" is a claim no test suite, however large, can actually back up — there's always an untested input, an untested interaction with some other part of the system, or an environment difference (a different OS, a different data volume) the tests never modeled. The honest framing is that tests reduce risk and catch regressions fast, not that they eliminate bugs entirely.
Red flagsAgreeing that comprehensive tests guarantee bug-free code, or not being able to give a concrete example of a bug category tests commonly miss (e.g. behavior that only shows up under real production load, or an untested combination of inputs).
Follow-up"Give one category of bug that a thorough unit test suite commonly still misses." (Anything that only emerges from real integration/scale conditions — a race condition under real concurrent load, a performance cliff at data volumes far larger than any test fixture uses, or a genuinely untested combination of two features that individually both have full coverage.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.