← All notes

Mocking in Python tests: pytest monkeypatch vs unittest.mock patch

Answer: The monkeypatch fixture helps with patching and mocking in tests; modifications are undone when the requesting test function or fixture finishes. The standard library's unittest.mock gives Mock, MagicMock and a patch() decorator.

monkeypatch

unittest.mock

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: pytest-dev/pytest (GitHub), How to monkeypatch/mock modules and environments (pytest docs), MIT (https://raw.githubusercontent.com/pytest-dev/pytest/main/LICENSE). Copyright (c) 2004 Holger Krekel and others; Python Software Foundation (docs.python.org), unittest.mock — mock object library, PSF-2.0 (https://docs.python.org/3/library/unittest.mock.html (page footer: licensed under the Python Software Foundation License Version 2; code examples Zero Clause BSD)). Copyright 2001 Python Software Foundation. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: pytest-dev/pytest (GitHub), How to monkeypatch/mock modules and environments (pytest docs), MIT (https://raw.githubusercontent.com/pytest-dev/pytest/main/LICENSE). Copyright (c) 2004 Holger Krekel and others; Python Software Foundation (docs.python.org), unittest.mock — mock object library, PSF-2.0 (https://docs.python.org/3/library/unittest.mock.html (page footer: licensed under the Python Software Foundation License Version 2; code examples Zero Clause BSD)). Copyright 2001 Python Software Foundation.

Cite this

Permanent ID: iil:note:mktgk2b5

iinventedlight. 2026. "Mocking in Python tests: pytest monkeypatch vs unittest.mock patch." iinventedlight Library, iil:note:mktgk2b5, version of 2026-11-16. https://iinventedlight.com/library/notes/python-mocking-monkeypatch-and-mock/. License: CC-BY-4.0.

@misc{iil_note_mktgk2b5,
  author = {{iinventedlight}},
  title = {{Mocking in Python tests: pytest monkeypatch vs unittest.mock patch}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-16},
  url = {https://iinventedlight.com/library/notes/python-mocking-monkeypatch-and-mock/},
  note = {Permanent ID iil:note:mktgk2b5. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-mocking-monkeypatch-and-mock.md.