1. Home
  2. Blog
  3. Test Automation

Test Automation

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.

9 min read
Test doubles explained: mocks, stubs, fakes, spies and dummies

Key takeaways

  • 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 Mock accepted a misspelled method in our test; create_autospec rejected 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?

  1. Is the dependency unused on this path? Use a dummy.
  2. Do you only need to control what it returns? Use a stub.
  3. Is the call itself the outcome, such as sending an email or publishing an event? Use a spy or a mock.
  4. Do many tests need realistic behaviour, such as storing and reading data? Build a fake.
  5. 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →