with patch('my_module.ExternalService') as MockService:
Testing Patterns

Meaning

Usage of unittest.mock.patch as a context manager to temporarily replace my_module.ExternalService with a mock object named MockService for testing.

Primary Function

Mocking

Communicative Purpose

Ensures test isolation by replacing external dependencies with controllable mock objects during test execution.

Pattern

with patch('module.Class') as Alias:

Core Structure

with patch('module.Class') as Alias:

Função primária

Mocking

Propósito comunicativo

Ensures test isolation by replacing external dependencies with controllable mock objects during test execution.

Situações de gatilho

Unit testing: isolating a function that calls an external API or service Integration testing: replacing a database connection with a deterministic mock Legacy code: intercepting calls to untestable dependencies without refactoring

Contextos

Unit test files using unittest.mock, test suites, test cases.

Padrão

with patch('module.Class') as Alias:

Estrutura central

with patch('module.Class') as Alias:

Slots de substituição

module_path: dotted string path to target class or function, alias: valid Python identifier for mock reference

Colocados típicos

  • patch
  • Mock
  • assert_called
  • assert_called_with
  • return_value
  • side_effect

Substituições comuns

  • patch.object: patches an object attribute rather than a module-level name
  • useful for instance attributes
  • patch.dict: patches dictionary entries rather than object attributes
  • @patch decorator: patches for entire test function
  • less precise scoping than context manager

Erros comuns

Failing to stop the patch, patching the wrong attribute, forgetting to assign the mock to a variable, not using autospec leading to overly permissive mocks.

Similar / contraste

patch.object (patches attribute on an object), patch.dict (patches dictionary items), unittest.mock.MagicMock (direct mock creation).

Interferências

Coming from JavaScript/Jest: may expect mock hoisting behavior where jest.mock() is hoisted to file top → Python's patch must be placed at the correct import resolution point, typically where the name is looked up not where it is defined

Família do chunk

  • unittest.mock patterns

Nuance

Do not use patch for dependencies you own and can refactor to accept via constructor injection — prefer explicit dependency injection for cleaner design. Patching has negligible runtime overhead but each patched test is harder to reason about than constructor-injected doubles. The patch target string must match where the name is looked up (usage site), not where it is defined, which is a common source of silent patching failures.

Efeito pragmático

Indicates a testing boundary where ExternalService is replaced with a test double.

Dica de memória

Like hiring a stunt double for a scene — the real actor steps out, the double performs exactly as directed, and when the scene ends the real actor returns.

Nota

Ensure the target string matches the import path used in the code under test.

Upgrade path

Consider using patch.object for more precise attribute patching or autospec for stricter mocks.

Frequência: HighFormulaicidade: Semi-fixedTipo de construção: context manager usage with unittest.mock.patchPrioridade de aquisição: Active recallPrioridade de output: OutputTag de espaçamento: Medium-term

Log in to save chunks.