Meaning
A Python unit test that uses unittest.mock.patch to replace a method of a class with a mock object, injecting the mock as a function argument so the test can verify interactions without executing the real method.
Primary Function
Replaces a target method with a mock during a test, isolating the unit under test and enabling verification of calls to the mocked method.
Communicative Purpose
Declares a test case where a specific method is substituted with a mock, allowing the test to assert how the method was called without invoking its real implementation.
Pattern
@patch('target') def test_function(mock):
Core Structure
@patch('target') def test_function(mock): # test body using mock
Função primária
Replaces a target method with a mock during a test, isolating the unit under test and enabling verification of calls to the mocked method.
Propósito comunicativo
Declares a test case where a specific method is substituted with a mock, allowing the test to assert how the method was called without invoking its real implementation.
Situações de gatilho
When writing unit tests for code that depends on a method from another class or module, and you need to isolate the unit under test from external dependencies, side effects, or expensive operations.
Contextos
Unit test modules using the unittest framework or pytest, typically within test functions or test class methods that apply the unittest.mock.patch decorator.
Padrão
@patch('target') def test_function(mock):
Estrutura central
@patch('target') def test_function(mock): # test body using mock
Slots de substituição
target: str (dotted path to class.method, e.g., 'module.Class.method'), function_name: str (valid Python identifier for test function), mock_param: str (valid Python identifier receiving the mock object)
Colocados típicos
- unittest.TestCase
- pytest
- mock.assert_called_once_with
- mock.assert_called_with
- patch.object
- patch.dict
Substituições comuns
- patch.object for patching attributes on objects
- patch.dict for temporarily modifying dictionaries
- using patch as a context manager (with patch(...) as mock:)
- using mock.Mock directly
Erros comuns
- Forgetting to pass the mock as an argument leads to a NameError because the mock is not injected. - Applying patch to a non‑existent attribute raises an AttributeError during test setup. - Assuming the mock replaces the attribute globally, causing side effects in other tests if the patch is not properly scoped. - Confusing patch.object with patch when targeting class attributes, which can result in the mock not being applied. - Forgetting to reset side_effect or return_value between tests, leading to test pollution.
Similar / contraste
- patch.object: patches a specific attribute on an object or class; useful when the target is an instance attribute rather than a dotted import path. - patch.dict: temporarily modifies a dictionary, restoring it after the block; works on mappings instead of callable attributes. - mock.Mock: creates a mock object directly without patching; requires manual injection rather than automatic argument passing. - unittest.mock.PropertyMock: used to mock properties or descriptors; handles the descriptor protocol unlike a plain method mock.
Interferências
Coming from Java: may expect @Mock annotation to inject fields directly; in Python unittest.mock the mock is passed as an explicit function argument → ensure the test function accepts the mock parameter. Coming from JavaScript/Jest: may assume mocks are automatically restored after each test; in Python, patch must be used as a decorator or context manager to guarantee proper cleanup → always use patch as a decorator or with statement to avoid test pollution.
Família do chunk
- unit testing
- mocking
- unittest.mock
Nuance
1. Not suitable when you need to exercise the real method’s behavior (e.g., testing side‑effects, timing, or resource usage). 2. Introduces minimal overhead—mock creation is lightweight, but excessive patching in tight loops can slow test suite execution. 3. The patch affects the target name as looked up at import time; if the module imports the object elsewhere under a different names elsewhere, those references are not mocked.
Efeito pragmático
Enables reliable, fast unit tests by isolating units from external dependencies, allowing safe refactoring of dependencies and focusing tests on interaction contracts rather than internal implementation.
Dica de memória
Think of @patch as a stunt double that steps in for the real actor during a dangerous stunt, letting you verify the stunt was called without risking the actual stunt.
Nota
When patching a class method, the mock replaces the method on the class itself, affecting all instances unless the patch is limited to a specific instance via patch.object.
Log in to save chunks.