All jobs / Backend developer / Testing
Backend developer interview question · 0–1 years
In a test, what is the difference between a stub, a mock and a fake?
The strongest answer
A stub returns canned answers so the code under test can run; a mock also records calls so the test can assert an interaction happened; a fake is a real but lightweight implementation, such as an in-memory repository
Why it works
Right — and the practical point is that asserting on a mock ties the test to how the code works, not to what it does.
What a good answer covers
- Stub: canned answers.
- Mock: asserts an interaction.
- Fake: a working lightweight version.
- Never mock the code under test.
Answers that fall short
- Close, but not the strongest: They are all test doubles standing in for a real dependency, and mocks are the ones you assert on
Correct as far as it goes; the interviewer wants the split — canned answers, recorded interactions, working substitute. - Weak: Mock is the modern name — the libraries call everything a mock, so the distinction is historical
The libraries blur the names; the concepts still differ, and they decide what your test is really asserting. - Red flag: I mock the class under test itself, so I can control exactly what it returns
Mocking the thing you are testing means the test passes no matter what the real code does.
Who gets asked this
More Testing questions
- Your repository tests run against an in-memory database and pass, but the same query fails in production…
- How do you test that POST /orders returns 201 with the right body, without deploying anything?
- A refactor that changed no behaviour broke forty tests. Each one asserts that a particular method was called…
- What would consumer-driven contract tests give you here?
- The service’s CI suite fails about one run in five for reasons unrelated to the change, and the team’s habit…
- A teammate calls their test a unit test, but it starts a database container and an HTTP server. Does the…