Skip to content

Lesson 4 of 9 · 26m

Mocking Without Lying to Yourself

Patch at the right boundary, assert behavior instead of implementation chatter, and recognize when a fake or integration test is more honest.

The worst test suites do not fail because mocks are absent. They fail because mocks are everywhere. Every object is fake, every call is expected, and the tests pass even after the real integration has been broken for weeks. Mocking is a scalpel for boundaries, not a substitute for design.

Patch where the object is looked up

unittest.mock.patch replaces a name in the module that uses it, not necessarily where it was defined:

# billing/service.py
from stripe import Customer

def create_customer(email):
    return Customer.create(email=email)

Patch billing.service.Customer, not stripe.Customer, because the service module imported its own reference:

from unittest.mock import patch

def test_create_customer_uses_email():
    with patch("billing.service.Customer") as customer:
        customer.create.return_value = {"id": "cus_123"}
        result = create_customer("sam@example.com")

    assert result == {"id": "cus_123"}
    customer.create.assert_called_once_with(email="sam@example.com")

This is the most common mock failure mode: the patch target is real, but the code under test uses a different binding.

Mock at ownership boundaries

A boundary you own internally is usually better tested directly. A boundary owned by someone else — SMTP, Stripe, S3, the filesystem clock — is a legitimate mock or fake. Ask: "can I run the real thing cheaply and deterministically?" If yes, prefer the real thing in an integration test. If no, isolate it.

Over-specified tests calcify refactoring

This test passes today and becomes noise after a harmless refactor:

client.get.assert_called_once_with(
    "https://api.example.test/v1/users",
    headers={"Authorization": "Bearer token"},
    timeout=3,
)

Sometimes exact call shape is the contract — especially for security headers or retry behavior. Often the meaningful contract is only: one outbound request, correct host, correct auth scheme. Assert what the business behavior needs, not every incidental keyword.

Fakes beat mocks for stateful collaborators

For a repository or cache, a small in-memory fake is often clearer than a mock with fifteen return values:

class FakeUserRepo:
    def __init__(self):
        self.users = {}

    def save(self, user):
        self.users[user.id] = user

    def get(self, user_id):
        return self.users[user_id]

The fake implements the same contract and lets tests exercise realistic sequences: save, update, fetch, delete. Mocks are good at verifying one interaction; fakes are good at preserving invariants across several.

Field notes

  • If a test needs five mocks, the unit under test is probably doing too much or the boundary is wrong.
  • autospec=True catches signature drift; use it when patching important interfaces.
  • Do not mock the object under test. That is a hallucinated success path.
  • Prefer dependency injection over monkeypatching module globals when you control the design.
  • Keep one or two high-level integration tests around heavily mocked units; otherwise there is no evidence the pieces still connect.

Was this lesson helpful?

Sign in to rate