Meaning
Temporarily replaces a named method or attribute on a specific object with a Mock that returns a fixed value, automatically restoring the original when the with-block exits. It solves the problem of testing code that depends on expensive, nondeterministic, or unavailable collaborators. You reach for it when you need to isolate a unit under test by controlling what a dependency returns without permanently modifying the object.
Primary Function
Test isolation
Communicative Purpose
Isolates units under test by temporarily replacing object methods with controllable mock objects that return predetermined values
Pattern
with patch.object(target, attribute, return_value=value) as mock_handle:
Core Structure
with patch.object(..., ..., return_value=...) as ...:
Função primária
Test isolation
Propósito comunicativo
Isolates units under test by temporarily replacing object methods with controllable mock objects that return predetermined values
Situações de gatilho
Unit testing: replacing an expensive API call on a service object to test business logic in isolation Integration testing: stubbing out database queries to avoid hitting real data stores Legacy code: substituting hard-to-instantiate dependencies that prevent test setup
Contextos
unittest.mock, pytest, Django test suites, Flask application testing
Padrão
with patch.object(target, attribute, return_value=value) as mock_handle:
Estrutura central
with patch.object(..., ..., return_value=...) as ...:
Slots de substituição
target: object instance or class to patch, attribute: str name of method or attribute to replace, value: return value for the mock, mock_handle: variable name for the mock object
Colocados típicos
- assert_called_once_with
- assert_called
- MagicMock
- patch
- unittest.TestCase
- call_count
Substituições comuns
- patch.object with side_effect instead of return_value (for raising exceptions or dynamic return values)
- patch decorator (function-level or class-level patching with longer scope)
- pytest monkeypatch fixture (pytest-native alternative with fixture scoping)
Erros comuns
Patching the instance instead of the class when the method is looked up on the class — the mock won't intercept calls from other code paths that access via the class. Fix by patching on the class itself. Forgetting the 'with' statement — calling patch.object without a context manager won't auto-restore the original attribute, causing test pollution across test cases. Using return_value on a non-callable attribute — return_value only takes effect when the mock is called as a function; for property-like attributes, use the new parameter instead. Patching after the target module has already imported the original — the local name binding still points to the unpatched original, so the patch has no visible effect.
Similar / contraste
patch (decorator form) — patches at module path level for entire test function scope, patch.dict — specifically for replacing dictionary entries, patch.multiple — patches several attributes in a single context manager
Interferências
Coming from JavaScript/Jest: may expect jest.spyOn(obj, 'method').mockReturnValue(val) which wraps and records calls on the real method — Python's patch.object replaces the attribute entirely with a fresh MagicMock, discarding the original until the block exits. Coming from Ruby/RSpec: may expect allow(obj).to receive(:method).and_return(val) which is a pure stub — patch.object creates a full mock that also supports call tracking and assertions.
Família do chunk
- patch
- patch.object
- patch.dict
- patch.multiple
- MagicMock
- Mock
- call
Nuance
Do not use when you need the real method to execute alongside mock verification — patch.object completely replaces the method, unlike a spy. The patch is scoped strictly to the with-block; any threads or async tasks that outlive the block will see the restored original, which can cause subtle timing bugs. Patching on a class vs an instance has different semantics: patching the class affects all instances and future attribute lookups, while patching an instance only affects that specific object's attribute.
Efeito pragmático
Enables deterministic, fast unit tests by eliminating external dependencies and controlling return values, preventing flaky tests caused by network calls, database state, or slow I/O.
Dica de memória
Like putting a stunt double in place of an actor for a dangerous scene — the double performs a controlled, predictable action, then the real actor steps back in when the scene is done.
Nota
return_value is a keyword argument to patch.object, not a property set on the resulting Mock. For raising exceptions instead of returning values, use side_effect=ExceptionClass. The as-clause variable is the MagicMock instance, which you can use for assertions after the code under test runs.
Upgrade path
patch.multiple for patching several attributes at once, or pytest's monkeypatch fixture for fixture-scoped patching with automatic teardown
Log in to save chunks.