Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Mocking and Monkeypatching

unittest.mock Basics

Learn Mock, MagicMock, return_value, side_effect and call assertions from the standard library's unittest.mock, and use them in pytest tests to fake collaborators.

monkeypatch swaps things out. A mock is the thing you swap in: an object that accepts any call, remembers exactly how it was used, and returns whatever you tell it to. Python's standard library provides them in unittest.mock, and pytest works with them directly, with no plugin needed.

Mocks answer two questions. First, "what should this dependency return?" (for example, a fake payment gateway that always approves). Second, "did my code call the dependency the way I expected?" (for example, was the email sent exactly once, to the right person?). This lesson covers both.

Mock objects remember everything

A Mock creates attributes and methods on demand. Every call is recorded.

Python Calling and inspecting a Mock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

return_value is what the call gives back. call_args is the most recent call, call_args_list is all of them, and method_calls records calls on child attributes.

Asserting how a mock was used

Instead of reading call_args yourself, use the built-in assertion helpers. They raise AssertionError with a helpful message when the expectation is not met.

Assertion Passes when
assert_called() called at least once
assert_called_once() called exactly once
assert_called_with(...) the last call used these arguments
assert_called_once_with(...) called exactly once, with these arguments
assert_any_call(...) some call used these arguments
assert_has_calls([call(...), ...]) these calls happened, in order
assert_not_called() never called
Python Assertion helpers and call()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

side_effect: errors, sequences and functions

return_value is fixed. side_effect is more flexible and has three forms:

  • An exception (class or instance): the call raises it. Perfect for testing error handling without breaking anything real.
  • An iterable: each call returns the next item, and the call after the last raises StopIteration.
  • A function: it is called with the same arguments and its return value is used.
Python The three forms of side_effect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A list that mixes exceptions and values is how you test retry logic: fail once, then succeed.

MagicMock supports Python's protocols

MagicMock is a Mock that also implements the "magic" (dunder) methods: len(), in, iteration, with, indexing and more. Use it when the code under test treats the object like a container or context manager. patch() creates a MagicMock by default.

Python MagicMock as a container and context manager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Putting a mock into a pytest test

Here is the real pattern: the function receives its collaborator as a parameter (dependency injection), and the test hands in a mock. No patching needed.

Python A mock inside a pytest test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second test is the valuable one: it proves a negative ("no email on failure") that is awkward to check any other way.

Mock, MagicMock, NonCallableMock

For everyday work, remember: use Mock for plain objects and callables, MagicMock when dunder methods are needed, and patch (next lesson) to install them. Two habits keep mocks honest:

  • Give mocks a spec so they only allow what the real object offers (covered in patch and autospec).
  • Assert on behaviour that matters (a charge happened, an email was not sent), not on every internal call. Tests tied to implementation details break when you refactor.

A bare Mock accepts typos silently. gateway.charge_card.assert_called_once() passes the attribute lookup but fails the assertion, while gateway.chrage.assert_called_once (missing parentheses) is never executed and the test passes without checking anything. Always call the assertion method, and prefer specs.

flowchart LR
    T["test"] -->|"arranges return_value / side_effect"| M["Mock"]
    C["code under test"] -->|"calls"| M
    M -->|"records calls"| R["call_args, call_count"]
    T -->|"asserts on"| R

The test arranges the answers, the code calls the mock, the test checks the record.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does setting side_effect to a list of values do?

    An iterable side_effect is consumed one item per call. Items that are exception instances are raised instead of returned.
  2. 2. Which assertion verifies that a mock was called exactly once with specific arguments?

    assert_called_once_with checks both the call count and the arguments. assert_called_with only checks the last call.
  3. 3. When do you need MagicMock instead of Mock?

    MagicMock pre-configures the dunder methods; plain Mock does not support them.
  4. 4. Why is mailer.send.assert_not_called() a useful check in a failure-path test?

    Mocks let you assert on things that should NOT happen, such as sending a receipt after a declined payment.

Summary

  • Mock and MagicMock fake collaborators and record every call.
  • return_value gives a fixed answer; side_effect raises errors, yields a sequence or runs a function.
  • Use assert_called_once_with, assert_not_called, assert_has_calls and friends, and always call them.
  • Passing mocks as arguments (dependency injection) needs no patching at all.
  • Assert on behaviour that matters, not on every internal call.

Next: patch and autospec