Glossary

Mock

A mock is a test double — an object that stands in for a real dependency during testing, allowing you to test code in isolation. Python's unittest.mock module (available since Python 3.3) provides Mock and MagicMock objects that automatically create attributes and methods on demand, record how they were called, and can be configured to return specific values or raise exceptions.

The primary tool for using mocks is unittest.mock.patch, which temporarily replaces an object in the module being tested with a mock. It can be used as a decorator (@patch('module.ClassName')) or a context manager (with patch('module.func') as m:). The key principle is to patch where the object is used, not where it is defined — if my_module imports requests.get, you patch my_module.requests.get, not requests.get.

Mocks are essential for testing code that depends on external services (APIs, databases, file systems, time), slow operations, or non-deterministic behaviour. However, overuse of mocking can make tests brittle and tightly coupled to implementation details. The pytest-mock plugin provides a mocker fixture that integrates unittest.mock.patch with pytest's fixture system, making mocking more ergonomic.

Related terms: pytest, Fixture

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.