Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Mocking & test isolationMiddleCommonPractical

When would you use pytest `monkeypatch` instead of `unittest.mock.patch`, and what should you patch?

Answer

`monkeypatch` is convenient when a pytest test needs temporary changes to attributes, dictionaries, environment variables, paths or the working directory; pytest automatically restores those changes after the requesting scope finishes. `unittest.mock.patch` is stronger when you need mocks with call assertions, autospec or detailed behavior control. In either case patch the name that the code under test actually looks up, not blindly the object where it was originally defined, and prefer explicit dependency injection when extensive patching starts to dominate the design.

Strong answer includes

  • uses monkeypatch for temporary pytest-managed state such as env vars and attributes
  • uses mock.patch when call verification or richer Mock behavior is required
  • patches where the dependency is looked up and recognizes excessive patching as a design smell

Practical example

A configuration test uses

Python example
monkeypatch.setenv("API_URL", "https://stub")

because the only goal is temporary process state. A service test uses

Python example
patch("orders.client.send", autospec=True)

because it must verify that

Python example
send()

was called once with the exact payload.

#pytest#monkeypatch#mocking#unittest-mock

Sources

pytest documentationpytest · Fixture scope, parametrization, markers and plugin architecturepytest Interview QuestionsAssertHired · 2026 Python QA/SDET recurrence signal for pytest fixtures, markers, monkeypatch, xdist, reporting and framework structureunittest — Unit testing frameworkPython Software Foundation · Baseline test-case, mock and assertion semantics shared across Python test tooling