Skip to main content

Testing and QA · Intermediate · 22 min

Choose between mocks, stubs and fakes in your tests

By Padding · Updated 18 Nov 2026
Python 3.15 · pytest 9.2.0

You will test a small checkout module with a dummy, a stub, a spy, an autospecced mock and an in-memory fake, and use them to find two bugs that a test built only from plain mocks lets through.

On this page

A unit test should not charge a real card, send a real email or wait for a currency service on the other side of the world. So you swap those collaborators for stand-ins, called test doubles. "Mock" has become the word for all of them, but the doubles do different jobs, and picking the wrong one is how a suite ends up green while the code is broken.

There are five jobs:

  • A dummy fills a slot the code never uses.
  • A stub gives canned answers to the questions the code asks.
  • A spy records what the code did, so the test can look afterwards.
  • A mock is set up to check that particular calls happened, with particular arguments.
  • A fake is a small working version of the real thing, such as an in-memory repository.

You will write tests for a checkout module that has two bugs in it on purpose. One test made only of plain unittest.mock.Mock objects passes on both bugs. By the end, a stub, an autospecced mock and a fake have caught them, and you will have a short rule for choosing the double each time.

Step 1 · Set up the project and the code under test

Make a throwaway project folder with a virtual environment and pin pytest:

Bash
mkdir -p ~/test-doubles-demo
cd ~/test-doubles-demo
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --quiet "pytest==9.2.0"
mkdir -p shop tests
touch shop/__init__.py

Tell pytest where the code and the shared test helpers live, so import shop and import doubles work from any test:

Bash
cat > pytest.ini <<'INI'
[pytest]
testpaths = tests
pythonpath = . tests
INI

Now the application. rates.py asks a currency service how many units of a currency one pound buys, and pricing.py uses it to show prices in the shopper's currency. The service address comes from an environment variable. The default is on the reserved .invalid domain, which never resolves, so a test that forgets to replace it fails at once instead of reaching the internet.

Bash
cat > shop/rates.py <<'PY'
import json
import os
import urllib.request


def fetch_rate(currency):
    """Return how many units of `currency` one British pound buys."""
    base = os.environ.get("RATES_API_URL", "https://rates.example.invalid")
    url = f"{base}/latest?from=GBP&to={currency}"
    with urllib.request.urlopen(url, timeout=5) as response:
        return json.load(response)["rate"]
PY

cat > shop/pricing.py <<'PY'
from shop.rates import fetch_rate


def to_local(amount_pence, currency):
    """Convert a price in pence to another currency, rounded to 2 places."""
    if currency == "GBP":
        return round(amount_pence / 100, 2)
    return round(amount_pence / 100 * fetch_rate(currency), 2)
PY

Next, the three collaborators of checkout: a payment gateway, a mailer and an order store. The gateway and mailer talk to the outside world. The API key is read from the environment when a charge is made, never written in the code. The order store is described by a Protocol. In production it would be a class backed by PostgreSQL, which this demo leaves out.

Bash
cat > shop/gateway.py <<'PY'
import json
import os
import urllib.request


class PaymentGateway:
    """Talks to the payment provider over HTTPS. Never call it from a unit test."""

    def __init__(self, base_url=None):
        self.base_url = base_url or os.environ.get(
            "PAYMENTS_API_URL", "https://payments.example.invalid"
        )

    def charge(self, amount_pence, currency, *, idempotency_key):
        """Charge the customer's saved card and return the provider's charge ID."""
        request = urllib.request.Request(
            f"{self.base_url}/charges",
            data=json.dumps({"amount": amount_pence, "currency": currency}).encode(),
            headers={
                "Authorization": f"Bearer {os.environ['PAYMENTS_API_KEY']}",
                "Content-Type": "application/json",
                "Idempotency-Key": idempotency_key,
            },
        )
        with urllib.request.urlopen(request, timeout=10) as response:
            return json.load(response)["id"]
PY

cat > shop/mailer.py <<'PY'
import smtplib
from email.message import EmailMessage


class Mailer:
    """Sends email through an SMTP server."""

    def __init__(self, host="localhost", port=25):
        self.host = host
        self.port = port

    def send(self, to, subject, body):
        message = EmailMessage()
        message["To"] = to
        message["From"] = "orders@shop.example"
        message["Subject"] = subject
        message.set_content(body)
        with smtplib.SMTP(self.host, self.port, timeout=10) as smtp:
            smtp.send_message(message)
PY

cat > shop/orders.py <<'PY'
from dataclasses import dataclass
from typing import Protocol


@dataclass
class Order:
    id: str
    email: str
    total_pence: int
    status: str = "pending"
    charge_id: str | None = None


class OrderRepository(Protocol):
    def add(self, order: Order) -> None: ...

    def get(self, order_id: str) -> Order | None: ...
PY

Last, checkout.py. Read it closely: it has two bugs, and the rest of the tutorial is about which doubles find them.

Bash
cat > shop/checkout.py <<'PY'
import uuid

from shop.orders import Order


def place_order(email, basket_pence, *, gateway, orders, mailer):
    """Charge for a basket, store the order and email a confirmation."""
    if not basket_pence:
        raise ValueError("basket is empty")
    total = sum(basket_pence)
    order = Order(id=uuid.uuid4().hex[:8], email=email, total_pence=total)
    orders.add(order)
    order.charge_id = gateway.charge(
        amount=total, currency="GBP", idempotency_key=order.id
    )
    order.status = "paid"
    mailer.send(email, f"Order {order.id} confirmed", f"We charged £{total / 100:.2f}.")
    return order
PY

place_order takes its collaborators as arguments. That choice, passing dependencies in, is what makes most of the doubles below possible without patching anything.

Check it worked

Bash
python -m pytest --version
python -c "import shop.checkout, shop.pricing; print('imports ok')"

The first line is pytest 9.2.0 and the second is imports ok.

Step 2 · Fill unused slots with dummies

The first rule of place_order is that an empty basket is refused before anything else happens. The test needs to pass a gateway, a store and a mailer, but none of them should be touched. Pass a plain object() for each. It has no charge, add or send, so if the code ever reached for one, the test would fail with an AttributeError:

Bash
cat > tests/test_dummies.py <<'PY'
import pytest

from shop.checkout import place_order


def test_empty_basket_is_refused_before_anything_else():
    unused = object()
    with pytest.raises(ValueError, match="basket is empty"):
        place_order("ada@example.com", [], gateway=unused, orders=unused, mailer=unused)
PY
python -m pytest -q tests/test_dummies.py

A dummy is the cheapest double there is. Reach for it whenever a signature demands an argument the path under test never uses. Prefer object() to Mock() here: a Mock answers every attribute and every call, so it would hide the very mistake the dummy is there to expose.

Check it worked

pytest prints 1 passed. To see the dummy do its job, temporarily move the if not basket_pence check below orders.add(order): the test fails with AttributeError: 'object' object has no attribute 'add'. Put the check back before you go on.

Step 3 · Stub the exchange rate and patch where the name is looked up

to_local needs one answer from the outside world: a rate. A stub supplies it. Because pricing.py imports fetch_rate rather than receiving it as an argument, you replace it with unittest.mock.patch.

Start with the mistake almost everyone makes once. Patch the function in the module that defines it:

Bash
cat > tests/test_pricing.py <<'PY'
from unittest.mock import patch

from shop.pricing import to_local


def test_naira_price_patched_in_the_wrong_place():
    with patch("shop.rates.fetch_rate", return_value=2000.0):
        assert to_local(1250, "NGN") == 25000.0
PY
python -m pytest -q tests/test_pricing.py || echo "pytest exit code: $?"

The test fails with a URLError: the real fetch_rate ran and tried to reach rates.example.invalid. When Python ran from shop.rates import fetch_rate, it copied a reference to the function into the shop.pricing namespace. to_local looks the name up there, so the patch in shop.rates changes a name nobody reads. Patch the place where the name is looked up:

Bash
cat > tests/test_pricing.py <<'PY'
from unittest.mock import patch

from shop.pricing import to_local


def test_naira_price_uses_the_stubbed_rate():
    with patch("shop.pricing.fetch_rate", return_value=2000.0):
        assert to_local(1250, "NGN") == 25000.0


def test_pounds_need_no_rate_lookup():
    with patch("shop.pricing.fetch_rate", side_effect=AssertionError("no lookup for GBP")):
        assert to_local(1250, "GBP") == 12.5


def test_shilling_price_with_monkeypatch(monkeypatch):
    monkeypatch.setattr("shop.pricing.fetch_rate", lambda currency: 170.0)
    assert to_local(1250, "KES") == 2125.0
PY
python -m pytest -q tests/test_pricing.py

The second test turns the stub round: side_effect makes any call raise, which proves pounds never trigger a lookup. The third does the same job as the first with pytest's monkeypatch fixture, which undoes the change after the test. Use whichever your team already uses; the "where it is looked up" rule is the same for both.

A stub answers questions; it does not check them. None of these tests asserts how fetch_rate was called, because the result, 25000.0, already tells you the rate was used. Shops that price in naira, shillings or cedis often get these rates from a paid service with a daily quota, which is one more reason to stub it in unit tests and spend real calls only on a small integration check.

Check it worked

pytest prints 3 passed. If you see a URLError again, one of the patch targets still says shop.rates.

Step 4 · Verify calls with a mock and stop it drifting with autospec

The gateway is different from the rate service. Charging a card is a side effect you care about, so the test should check the call itself: right amount, right currency, an idempotency key. That is the job of a mock. Write two versions of the same test, one with a plain Mock and one with create_autospec, which builds a mock from the real class and refuses calls that do not fit its method signatures:

Bash
cat > tests/test_checkout_mocks.py <<'PY'
from unittest.mock import Mock, create_autospec

from shop.checkout import place_order
from shop.gateway import PaymentGateway
from shop.mailer import Mailer


def test_place_order_with_plain_mocks():
    gateway = Mock()
    gateway.charge.return_value = "ch_123"
    orders = Mock()
    mailer = Mock()

    order = place_order("ada@example.com", [1250, 499], gateway=gateway, orders=orders, mailer=mailer)

    gateway.charge.assert_called_once_with(amount=1749, currency="GBP", idempotency_key=order.id)
    orders.add.assert_called_once_with(order)
    assert order.status == "paid"


def test_place_order_with_autospec():
    gateway = create_autospec(PaymentGateway, instance=True)
    gateway.charge.return_value = "ch_123"
    orders = Mock()
    mailer = create_autospec(Mailer, instance=True)

    order = place_order("ada@example.com", [1250, 499], gateway=gateway, orders=orders, mailer=mailer)

    gateway.charge.assert_called_once_with(1749, "GBP", idempotency_key=order.id)
    orders.add.assert_called_once_with(order)
    assert order.status == "paid"
PY
python -m pytest -q tests/test_checkout_mocks.py || echo "pytest exit code: $?"

The plain-mock test passes. The autospec test fails with a TypeError that says something like missing a required argument: 'amount_pence'. That is the first bug: checkout.py calls charge(amount=...), but the real method's parameter is amount_pence. In production, every order would crash at the till. The plain Mock accepted the wrong name because a Mock accepts anything, and the test's own assert_called_once_with(amount=...) copied the mistake from the code. A mock built by hand only knows what you told it.

Fix the call in checkout.py. The rest of the file stays as it was, including the second bug:

Bash
cat > shop/checkout.py <<'PY'
import uuid

from shop.orders import Order


def place_order(email, basket_pence, *, gateway, orders, mailer):
    """Charge for a basket, store the order and email a confirmation."""
    if not basket_pence:
        raise ValueError("basket is empty")
    total = sum(basket_pence)
    order = Order(id=uuid.uuid4().hex[:8], email=email, total_pence=total)
    orders.add(order)
    order.charge_id = gateway.charge(total, "GBP", idempotency_key=order.id)
    order.status = "paid"
    mailer.send(email, f"Order {order.id} confirmed", f"We charged £{total / 100:.2f}.")
    return order
PY
python -m pytest -q tests/test_checkout_mocks.py || echo "pytest exit code: $?"

Now the results swap: the autospec test passes and the plain-mock test fails, because it still expects amount=. A test that passed on broken code and fails on fixed code is worse than no test. Delete it, and keep only the autospec version:

Bash
cat > tests/test_checkout_mocks.py <<'PY'
from unittest.mock import Mock, create_autospec

from shop.checkout import place_order
from shop.gateway import PaymentGateway
from shop.mailer import Mailer


def test_place_order_with_autospec():
    gateway = create_autospec(PaymentGateway, instance=True)
    gateway.charge.return_value = "ch_123"
    orders = Mock()
    mailer = create_autospec(Mailer, instance=True)

    order = place_order("ada@example.com", [1250, 499], gateway=gateway, orders=orders, mailer=mailer)

    gateway.charge.assert_called_once_with(1749, "GBP", idempotency_key=order.id)
    orders.add.assert_called_once_with(order)
    assert order.status == "paid"
PY
python -m pytest -q tests/test_checkout_mocks.py

Two details are worth knowing. An autospecced mock compares calls through the real signature, so charge(1749, "GBP", ...) and charge(amount_pence=1749, currency="GBP", ...) count as the same call. And patch takes autospec=True too, as in patch("shop.pricing.fetch_rate", autospec=True, return_value=2000.0), so patched functions get the same protection.

Check it worked

The last run prints 1 passed. If you make currency keyword-only in gateway.py (def charge(self, amount_pence, *, currency, idempotency_key)), this test fails with a TypeError, because checkout.py still passes the currency by position. Undo the change afterwards.

Step 5 · Record outgoing email with a spy

For the confirmation email, you care about what was sent, not about the exact sequence of calls. A spy fits: a small class that does no sending and keeps every message, so the test can inspect them in plain Python. Put shared doubles in tests/doubles.py:

Bash
cat > tests/doubles.py <<'PY'
class RecordingMailer:
    """A spy: sends nothing and remembers every message."""

    def __init__(self):
        self.sent = []

    def send(self, to, subject, body):
        self.sent.append({"to": to, "subject": subject, "body": body})
PY

cat > tests/test_spy.py <<'PY'
import inspect
from unittest.mock import Mock, create_autospec

from doubles import RecordingMailer
from shop.checkout import place_order
from shop.gateway import PaymentGateway
from shop.mailer import Mailer


def test_customer_gets_one_confirmation_naming_the_order():
    gateway = create_autospec(PaymentGateway, instance=True)
    gateway.charge.return_value = "ch_123"
    mailer = RecordingMailer()

    order = place_order("ada@example.com", [1250, 499], gateway=gateway, orders=Mock(), mailer=mailer)

    assert len(mailer.sent) == 1
    message = mailer.sent[0]
    assert message["to"] == "ada@example.com"
    assert order.id in message["subject"]
    assert "£17.49" in message["body"]


def test_recording_mailer_matches_the_real_mailer():
    assert inspect.signature(RecordingMailer.send) == inspect.signature(Mailer.send)
PY
python -m pytest -q tests/test_spy.py

The assertions read like the requirement: one email, to the customer, naming the order, with the right total. A hand-written double can drift from the real class just like a plain mock, so the second test compares the two send signatures and fails if someone changes one without the other.

If you want a spy that also does the real work, Mock(wraps=real_object) passes every call through and records it. That is handy for an in-process helper, but never wrap the real Mailer in a unit test: it would still send.

Check it worked

pytest prints 2 passed. Add a parameter to Mailer.send and the signature test fails. Undo it afterwards.

Step 6 · Replace the mock-heavy test with a fake

The autospec test still passes orders=Mock() and checks orders.add.assert_called_once_with(order). That proves add was called. It does not prove the order was stored as paid. A real database stores the row when add runs; changing the Python object afterwards changes nothing in the table. A fake makes that behaviour testable: a small working repository that keeps copies of orders in a dictionary, the way a database keeps rows.

Rewrite tests/doubles.py with the fake added:

Bash
cat > tests/doubles.py <<'PY'
import copy


class RecordingMailer:
    """A spy: sends nothing and remembers every message."""

    def __init__(self):
        self.sent = []

    def send(self, to, subject, body):
        self.sent.append({"to": to, "subject": subject, "body": body})


class InMemoryOrderRepository:
    """A fake: a working order store that keeps copies in a dict.

    Like a database, it saves the order as it was when add() ran.
    Later changes to the Order object are not saved.
    """

    def __init__(self):
        self._rows = {}

    def add(self, order):
        if order.id in self._rows:
            raise ValueError(f"duplicate order {order.id}")
        self._rows[order.id] = copy.deepcopy(order)

    def get(self, order_id):
        row = self._rows.get(order_id)
        return copy.deepcopy(row) if row else None

    def __len__(self):
        return len(self._rows)
PY

cat > tests/test_checkout.py <<'PY'
from unittest.mock import create_autospec

import pytest

from doubles import InMemoryOrderRepository, RecordingMailer
from shop.checkout import place_order
from shop.gateway import PaymentGateway


def make_gateway():
    gateway = create_autospec(PaymentGateway, instance=True)
    gateway.charge.return_value = "ch_123"
    return gateway


def test_paid_order_is_stored_as_paid():
    orders = InMemoryOrderRepository()

    order = place_order("ada@example.com", [1250, 499], gateway=make_gateway(), orders=orders, mailer=RecordingMailer())

    stored = orders.get(order.id)
    assert stored.status == "paid"
    assert stored.charge_id == "ch_123"
    assert stored.total_pence == 1749


def test_declined_card_stores_nothing():
    gateway = make_gateway()
    gateway.charge.side_effect = RuntimeError("card declined")
    orders = InMemoryOrderRepository()
    mailer = RecordingMailer()

    with pytest.raises(RuntimeError, match="card declined"):
        place_order("ada@example.com", [1250], gateway=gateway, orders=orders, mailer=mailer)

    assert len(orders) == 0
    assert mailer.sent == []
PY
python -m pytest -q tests/test_checkout.py tests/test_checkout_mocks.py || echo "pytest exit code: $?"

Both fake tests fail, and the mock-heavy test still passes. The first fake test shows the stored order is 'pending': the second bug. checkout.py stores the order and then marks it paid, so the database would hold every order as unpaid. The second fake test shows the knock-on effect: when the card is declined, the order has already been stored. The Mock() repository could not see either problem. It recorded a call and agreed with whatever the test asked, so the test was checking the mock, not the shop.

Fix checkout.py so it charges first and stores a finished order:

Bash
cat > shop/checkout.py <<'PY'
import uuid

from shop.orders import Order


def place_order(email, basket_pence, *, gateway, orders, mailer):
    """Charge for a basket, store the order and email a confirmation."""
    if not basket_pence:
        raise ValueError("basket is empty")
    total = sum(basket_pence)
    order_id = uuid.uuid4().hex[:8]
    charge_id = gateway.charge(total, "GBP", idempotency_key=order_id)
    order = Order(
        id=order_id, email=email, total_pence=total, status="paid", charge_id=charge_id
    )
    orders.add(order)
    mailer.send(email, f"Order {order.id} confirmed", f"We charged £{total / 100:.2f}.")
    return order
PY
python -m pytest -q tests/test_checkout.py

The fake tests now check outcomes, so they keep passing whether place_order calls add once, uses a transaction or batches writes later. The mock-heavy file adds nothing they do not cover, and its orders.add.assert_called_once_with(order) would break on any such refactor. Delete it:

Bash
rm tests/test_checkout_mocks.py

A fake is only useful while it behaves like the real store. When you have the real repository, run one shared set of contract tests against both the fake and the real class, so they cannot drift apart.

Check it worked

tests/test_checkout.py prints 2 passed, and ls tests no longer lists test_checkout_mocks.py.

Step 7 · Pick the double by its job and run the whole suite

Before you write a double, ask what the test needs from the collaborator:

  • Nothing, it only fills a slot: a dummy, object().
  • An answer, such as a rate or a lookup: a stub, through an argument or patch with return_value. Do not assert on how it was called.
  • A record of what was sent out, such as email or events: a spy you can read like data.
  • Proof that one side effect happened exactly so, such as a charge or a message to another team's system: an autospecced mock with assert_called_once_with. Keep this for calls that cross a boundary you do not own.
  • Behaviour that keeps state, such as a store, a cache or a queue: a fake, with contract tests against the real one.

Two warning signs that a test is over-mocked: it mocks something your own team wrote and could run for real, or its assertions repeat the lines of the function under test. Both mean the test will pass on broken code and fail on good refactors.

Run everything:

Bash
python -m pytest -v

Check it worked

pytest lists eight tests across test_checkout.py, test_dummies.py, test_pricing.py and test_spy.py, and ends with 8 passed. No test needed the network, an SMTP server or an API key.

Step 8 · Clean up

Leave the virtual environment and remove the demo project:

Bash
deactivate
cd ~
rm -rf ~/test-doubles-demo

Check it worked

ls ~/test-doubles-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.