Testing & QA
Test Doubles (Mocks, Stubs, Spies, Fakes)
The idea, in plain English
A test double is a stand-in you swap in for a real dependency during a test — like a stunt double who stands in for the actor during the dangerous scene. If your code sends real emails or charges real cards, you don't want that happening every test run. So you replace the real emailer with a lookalike. A STUB gives canned answers. A FAKE is a lightweight working version (like an in-memory store). A SPY quietly records how it was called. A MOCK is a stand-in with built-in expectations about how it should be used.
How it works
- 1Find the real dependency you don't want to actually run — a mailer, a payment gateway, a clock.
- 2Build a stand-in with the same shape (the same function names) so your code can't tell the difference.
- 3Have the stand-in record what it was asked to do (that's the 'spy' part) instead of really doing it.
- 4After the action, inspect those recordings to assert your code called the dependency correctly.
When you'd use it
Use test doubles whenever the real thing is slow, costs money, is unreliable, or has side effects you don't want in a test — sending emails, calling payment APIs, hitting a network. They let you test YOUR logic without dragging the whole outside world along.
Common beginner mistakes
- Faking so much that the test only checks your fakes, not your real code. If everything is a double, you've tested nothing real.
- Making the double behave differently from the real thing. If your fake mailer never fails but the real one sometimes does, your tests give false confidence.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
notified Ada
no email on file
Emails the spy recorded: 1
First recorded: ada@x.com: Welcome!Not sure this is the right topic? See the learning paths → or where this leads →