Testing interview question · Most asked
What's the difference between mocks, stubs, fakes and spies?
Summary
Stubs return canned answers; mocks additionally verify that expected interactions happened; fakes are working lightweight implementations (in-memory repository); spies wrap real objects and record calls. All are 'test doubles'.
Longer Answer
Overusing mocks couples tests to implementation and gives false confidence when the mocked contract drifts from reality. Prefer fakes for repositories and real infrastructure via containers for integration tests.
Key Points
- Stub: canned responses
- Mock: verifies interactions
- Fake: simplified real implementation
- Spy: records calls on real object
- Don't over-mock
Comparison / Tradeoffs
| Double | Returns data | Verifies calls | Has logic |
|---|---|---|---|
| Stub | Yes | No | No |
| Mock | Yes | Yes | No |
| Fake | Yes | No | Yes |
| Spy | Real | Yes (records) | Real |