How do you choose between a stub, mock, spy, fake and the real dependency?
Answer
Choose the simplest collaborator that preserves the behavior the test needs to trust. Use a stub to drive a specific branch, a mock or spy only when an externally meaningful interaction is the behavior, a fake for reusable stateful behavior, and the real dependency when fidelity outweighs speed and setup cost. Keep at least one contract or integration check wherever a double could drift from reality.
Strong answer includes
- starts from the behavior and test boundary
- avoids interaction assertions for implementation details
- pairs doubles with contract or integration evidence
Practical example
A candidate testing a checkout service stubs the tax-calculation client to return a fixed value for the order-total test, but keeps a separate contract test against the real tax API so a schema change in production is still caught even though the unit test never talks to it.