Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code
Test doubles are stand-ins for real dependencies such as payment gateways, mailers and databases. Learn the five classic kinds, what each one checks, when to pick which, and how a plain mock can hide bugs, using one small Python example we ran in pytest.
- Test doubles replace real dependencies in tests. The five classic types are dummy, stub, spy, mock and fake.
- Stubs and fakes support state checks (was the result right?); spies and mocks support behaviour checks (was the right call made?).
- A plain
Mockaccepted a misspelled method in our test;create_autospecrejected both the typo and a wrong argument count. - All six tests in our example passed in 0.52 seconds with pytest 9.2.0 on Python 3.13.
Unit tests should be fast, repeatable and focused. Real dependencies get in the way: a payment gateway charges money, a mailer sends email, an exchange-rate API changes every minute. Test doubles are the objects you put in their place, much as a stunt double stands in for an actor.
The term and the five-way split come from Gerard Meszaros’s book xUnit Test Patterns. Teams often say “mock” for all of them, and that loose language leads to tests that check the wrong thing. Below, one small checkout class is tested with each type of double. We ran all of it with pytest 9.2.0 on Python 3.13.6, and every test passed. For the mocking library itself, see our Python mocking guide.
What are test doubles?
A test double is any object that replaces a real collaborator during a test. The code under test cannot tell the difference, because the double offers the same methods. What differs between the types is how much they do and what you check afterwards:
- Dummy: passed in but never used.
- Stub: returns fixed answers.
- Spy: a stub that also records how it was called.
- Mock: set up with expectations about calls, which the test verifies.
- Fake: a working but simplified implementation, such as an in-memory database.
The code under test
Our Checkout class converts a price, charges a payment provider and emails a receipt. It needs four collaborators:
class Checkout:
def __init__(self, rates, payments, mailer, logger):
self.rates, self.payments, self.mailer, self.logger = rates, payments, mailer, logger
def place(self, order_id, amount_usd, currency, email):
rate = self.rates.get_rate("USD", currency)
total = round(amount_usd * rate, 2)
if not self.payments.charge(order_id, total, currency):
return "declined"
self.mailer.send(email, f"Order {order_id} paid: {total} {currency}")
return total
Using the real versions would hit a live rate API, a payment provider and an SMTP server. Each of the four parameters gets a different kind of double.
Dummy: fills a slot
The logger is required by the constructor but place never uses it. A dummy satisfies the signature. Ours goes further and fails loudly if anything touches it:
class DummyLogger:
def __getattr__(self, name):
raise AssertionError("logger should not be used")
Many people pass None as a dummy, which is fine when the code never checks the type. The explosive version documents the assumption and catches the day someone adds logging without updating the test.
Stub: canned answers
Exchange rates change constantly, which would make assertions impossible. A stub returns a fixed value:
class StubRates:
def get_rate(self, src, dst):
return 83.0
With the rate fixed at 83.0, a 50 USD order must total 4150.0 INR, and our test asserted exactly that. Stubs control the inputs your code receives from its dependencies. They are ideal for simulating awkward cases such as a timeout, an empty list or an error response.
Spy: records what happened
For the mailer we care that a receipt is sent with the right text. A spy stores each call so the test can inspect them afterwards:
class SpyMailer:
def __init__(self):
self.sent = []
def send(self, to, body):
self.sent.append((to, body))
def test_stub_and_spy():
mailer = SpyMailer()
co = Checkout(StubRates(), FakePayments(10_000), mailer, DummyLogger())
assert co.place("A1", 50, "INR", "demo@example.com") == 4150.0
assert mailer.sent == [("demo@example.com", "Order A1 paid: 4150.0 INR")]
The spy is passive: it never fails on its own. You write ordinary assertions against what it recorded, after the action. That keeps the test in the familiar arrange, act, assert order.
Fake: a small working version
Payment logic has rules: a charge fails if funds are low or the same order is charged twice. A fake implements those rules in memory:
class FakePayments:
def __init__(self, balance):
self.balance, self.charges = balance, {}
def charge(self, order_id, amount, currency):
if order_id in self.charges or amount > self.balance:
return False
self.balance -= amount
self.charges[order_id] = amount
return True
def test_fake_declines_duplicate_charge():
pay = FakePayments(10_000)
co = Checkout(StubRates(), pay, SpyMailer(), DummyLogger())
co.place("A1", 50, "INR", "demo@example.com")
assert co.place("A1", 50, "INR", "demo@example.com") == "declined"
assert pay.balance == 5850.0
The second order was declined and only one charge left the balance, so the test checks real state. Fakes shine when many tests share a dependency, because one fake replaces dozens of separate stub setups. The cost is that a fake is real code that can drift from the real service, so keep it small and test it against the real thing occasionally. In-memory SQLite in place of a production database is a common fake.
Mock: verifies interactions
Sometimes the only observable effect is a call to another system. A mock lets you assert that the call happened, with the exact arguments:
from unittest.mock import Mock
def test_mock_verifies_interaction():
payments = Mock()
payments.charge.return_value = True
mailer = Mock()
co = Checkout(StubRates(), payments, mailer, DummyLogger())
co.place("B2", 10, "INR", "demo@example.com")
payments.charge.assert_called_once_with("B2", 830.0, "INR")
mailer.send.assert_called_once()
Strictly, Meszaros defines a mock as an object that knows its expectations in advance and fails during the call. Python’s unittest.mock.Mock is technically closer to a spy, since you verify after the fact, but it plays the mock role in practice. Mocks are best at boundaries you do not own, such as an external API, where the call itself is the requirement.
When mocks lie: autospec
A plain Mock accepts any attribute and any arguments. That flexibility hides bugs. We ran two tests to prove it:
def test_plain_mock_hides_typo():
mailer = Mock()
mailer.sned("x", "y") # typo is silently accepted
assert mailer.sned.called
def test_autospec_catches_typo():
mailer = create_autospec(SpyMailer, instance=True)
with pytest.raises(AttributeError):
mailer.sned("x", "y")
def test_autospec_catches_wrong_signature():
mailer = create_autospec(SpyMailer, instance=True)
with pytest.raises(TypeError):
mailer.send("only-one-arg")
...... [100%]
6 passed in 0.52s
The plain mock happily recorded a call to a method that does not exist. If production code had that typo, the test would still pass. create_autospec copies the real class’s methods and signatures, so it raised AttributeError for the typo and TypeError for the missing argument. Use autospec, or Mock(spec=RealClass), by default.
Test doubles compared
| Type | Returns data? | Records calls? | Has logic? | You assert on |
|---|---|---|---|---|
| Dummy | No | No | No | Nothing |
| Stub | Yes, fixed | No | No | The result of the code under test |
| Spy | Optional | Yes | No | Recorded calls, after acting |
| Mock | Optional | Yes | No | Expected calls and arguments |
| Fake | Yes, computed | Sometimes | Yes, simplified | Resulting state |
Which test double should you use?
- Is the dependency unused on this path? Use a dummy.
- Do you only need to control what it returns? Use a stub.
- Is the call itself the outcome, such as sending an email or publishing an event? Use a spy or a mock.
- Do many tests need realistic behaviour, such as storing and reading data? Build a fake.
- Is it cheap, fast and deterministic already? Use the real object. Doubles are a cost, not a goal.
A useful rule: prefer state checks over interaction checks. Tests that assert on results survive refactoring; tests that assert on every internal call break whenever the implementation changes. Our unit vs integration testing guide explains where real dependencies belong instead.
Common mistakes
- Mocking what you own. Replacing your own simple classes with mocks couples tests to internals. Mock at system boundaries.
- Over-specified mocks. Asserting every call and argument makes tests brittle. Assert only what matters to the requirement.
- Unspecced mocks. As our test showed, a plain mock accepts typos. Always add a spec.
- Fakes without their own tests. A buggy fake makes every test that uses it wrong. Run a shared contract test against both fake and real implementations, as described in our API contract testing guide.
- Doubles everywhere. If every collaborator is replaced, the test proves very little. Balance with integration tests, following the test pyramid.
Final thoughts
Test doubles are a vocabulary as much as a technique. Saying “stub the rates, spy on the mailer, fake the payments” tells a teammate exactly what a test checks. Use stubs and fakes for state, spies and mocks for interactions that matter, dummies for unused slots, and always spec your mocks. In pytest, fixtures are a tidy home for these doubles; see our pytest fixtures guide.
Frequently asked questions
What is the difference between a mock and a stub?
A stub provides fixed answers so the test can check results. A mock records or expects calls so the test can check that the right interaction happened with the right arguments.
What is a fake in testing?
A fake is a lightweight working implementation of a dependency, such as an in-memory repository or payment service, that behaves realistically but takes shortcuts unsuitable for production.
What is a test spy?
A spy is a stub that also records how it was called. After running the code, the test inspects the recorded calls with normal assertions.
Why use create_autospec instead of Mock?
A plain Mock accepts any method name and any arguments, so typos pass silently. create_autospec copies the real class’s interface and raises errors for missing methods or wrong signatures.
Should I mock everything in unit tests?
No. Replace slow, non-deterministic or external dependencies, but use real objects where they are cheap and reliable. Too many doubles make tests brittle and less meaningful.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.