Mocking in pytest: Mock, patch and monkeypatch explained
Test code that calls payment providers, email, the clock or randomness: Mock, MagicMock, side_effect, where to patch, monkeypatch, and when not to mock.
Real code talks to things you can't use in a test: a payment provider that charges real money, an email service that writes to real customers, an API that's slow or down, a clock that reads a different time every run. Mocking replaces those with stand-ins you control, so your tests are fast, safe and repeatable.
Test doubles
A stand-in is called a test double:
| Double | What it does |
|---|---|
| stub | returns canned answers |
| fake | a working, simplified version (an in-memory store) |
| mock | records how it was used, so the test can check the calls |
The simplest double needs no library at all. If the code takes its dependency as an argument, pass your own object:
class FakeGateway:
def __init__(self):
self.charges = []
def charge(self, amount):
self.charges.append(amount)
return f"R-{len(self.charges)}"
def test_charges_the_cart_total():
gateway = FakeGateway()
place_order([("Rake", 1999, 1)], gateway)
assert gateway.charges == [1999]That's dependency injection, and it's the easiest code to test.
Mock: an object that accepts any call
unittest.mock.Mock (standard library) accepts any method call and remembers it:
from unittest.mock import Mock
mailer = Mock()
send_shipping_email(order, mailer)
mailer.send.assert_called_once_with("ada@example.com", "Order 42 is on its way", "Track: NL123")Configure answers with return_value, check calls with assert_called_once_with,
assert_not_called, call_count and call_args. Use Mock(spec=RealClass) so typos in method
names fail instead of silently working.
side_effect: errors, sequences, retries
client = Mock()
client.get.side_effect = [TimeoutError(), TimeoutError(), {"USD": 1.08}]
assert fetch_rates(client) == {"USD": 1.08}
assert client.get.call_count == 3A list as side_effect gives one item per call; exceptions in it are raised. That's how you test
retry logic: two timeouts, then success, and call_count proves how many attempts were made. A
single exception (side_effect = TimeoutError()) raises on every call.
MagicMock: context managers and iteration
from unittest.mock import MagicMock
warehouse = MagicMock()
warehouse.connect.return_value.__enter__.return_value = [{"sku": "A", "stock": 2}]
with warehouse.connect() as rows: # rows is the list above
...Read the chain as: what connect() returns, what entering it returns. Check it was closed with
warehouse.connect.return_value.__exit__.assert_called_once().
patch: replacing what a module uses
When the code imports its dependency directly, replace it for the duration of the test:
from unittest.mock import patch
def test_pay_charges_the_total():
with patch("checkout.charge", return_value="P-1") as charge:
assert pay({"card": "tok", "total": 2499}) == "P-1"
charge.assert_called_once_with("tok", 2499)The rule everyone trips over: patch where the name is looked up. checkout.py did
from payments import charge, so it has its own reference: patch("checkout.charge") works,
patch("payments.charge") doesn't. patch also works as a decorator, and patch.object(obj, "name") patches an object you already have.
monkeypatch: pytest's own patching fixture
def test_live_mode(monkeypatch):
monkeypatch.setenv("PAYMENT_MODE", "live")
monkeypatch.delenv("MAX_RETRIES", raising=False)
assert payment_settings() == {"mode": "live", "retries": 3}setenv, delenv, setattr, setitem and chdir, all undone automatically when the test
ends. Never set os.environ directly in a test: the change leaks into every test after it.
Time and randomness
A test that reads the real clock passes at 16:59 and fails at 17:00. Make the code read time through something you can replace, then replace it:
def test_happy_hour_on_friday(monkeypatch):
monkeypatch.setattr(promos, "now", lambda: datetime(2026, 3, 6, 17, 0))
assert promos.happy_hour() is TrueRandomness gets the same treatment: patch random.choice, or seed the generator.
When not to mock
Mock the boundaries of your system (payments, email, HTTP, queues, the clock), not your own code. A test that patches your own VAT function passes even when the VAT calculation is wrong, because it never runs. Signs of over-mocking: more setup than test, assertions about which internal helpers were called, and tests that break when you refactor without changing behaviour.
Practise it
Mastering pytest has a whole module on mocking, with exercises that check you patched the right place: the real payment function refuses to run in tests, so a patch in the wrong place fails immediately.
Questions and answers
- What is the difference between Mock and MagicMock?
- MagicMock is a Mock that also supports Python's special methods: you can use it in a with statement, iterate over it or call len() on it, and configure what those return. Plain Mock doesn't support them.
- Where should I patch a function?
- Where it's looked up, not where it's defined. If checkout.py does `from payments import charge`, patch checkout.charge, because checkout has its own reference to the function.
- Should I use monkeypatch or unittest.mock.patch?
- Both restore everything after the test. monkeypatch is simplest for environment variables, attributes and dictionary entries; patch gives you a Mock that records calls. They combine well: monkeypatch.setattr(module, 'name', Mock()).
- What should I not mock?
- Your own logic. Mock the boundaries your code doesn't control, like payment providers, email, HTTP APIs, the clock and randomness, and let your own functions run for real so the tests actually check them.
Practise it
Read next
- pytest fixtures explained: scope, yield, conftest.py and factories
How pytest fixtures work: requesting them, scopes, yield teardown, conftest.py, parametrized and autouse fixtures, and factory fixtures, with real examples.
- Testing with pytest: run, read and write Python tests
How to run pytest, read a failing test, select tests with markers and -k, share setup with fixtures, cover many cases with parametrize, and test exceptions.
- Learn pytest by catching real bugs: a hands-on course
Learn pytest from your first assert to fixtures, mocking and a full shop test suite. Real pytest runs in your browser, and your tests must catch planted bugs.