Mock
01 / 02

Mock, MagicMock & Configuring Behavior

Mock: Mock, MagicMock & Configuring Behavior

unittest.mock (Python standard library) provides Mock, MagicMock, and patch for replacing real dependencies -- network calls, databases, file I/O -- with controllable fake objects during a test, isolating the code under test from its real collaborators.

Basic Mock Behavior

from unittest.mock import Mock, MagicMock

m = Mock()

# Any attribute access or call auto-generates a child Mock -- no
# pre-configuration needed, but a typo'd name silently "succeeds"
# too, which is why spec/autospec exist (see next page).
m.anything.you.want()

# Configure a return value for when the mock is CALLED
mock_fetch = Mock(return_value={"status": "ok"})
mock_fetch()  # -> {"status": "ok"}

# side_effect: more flexible than a static return_value
mock_fetch.side_effect = ValueError("bad input")  # raises when called
mock_fetch.side_effect = [1, 2, 3]  # returns successive values per call
mock_fetch.side_effect = lambda x: x * 2  # computed dynamically

# MagicMock adds support for Python's magic/dunder methods --
# plain Mock() doesn't implement __len__, __iter__, __enter__, etc.
mm = MagicMock()
len(mm)          # works -- returns 0 by default
for _ in mm: ...  # works -- MagicMock supports __iter__

len(Mock())       # TypeError -- plain Mock has no __len__

Verifying How a Mock Was Called

mock_save = Mock()
mock_save(user_id=42, name="Alice")

mock_save.assert_called_once_with(user_id=42, name="Alice")
mock_save.assert_called()          # at least once, any args

other_mock = Mock()
other_mock.assert_not_called()     # verify a code path was correctly avoided

# For a mock called multiple times with different args, checking a
# SEQUENCE of calls (not just the most recent one):
from unittest.mock import call
mock_log = Mock()
mock_log("start")
mock_log("processing")
mock_log("done")
mock_log.assert_has_calls([call("start"), call("done")])  # subsequence, in order

# Raw introspection for custom assertions
mock_log.call_count       # 3
mock_log.call_args        # most recent call's args -- call("done")
mock_log.call_args_list   # every call's args, in order

# Reset call history mid-test without losing configured behavior
mock_log.reset_mock()

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free