with patch.object(MyClass, 'method', return_value='mocked'):
Testing Patterns

Meaning

A context manager that temporarily replaces a method with a mock returning a specified value, used to isolate units under test.

Primary Function

Temporarily replace a method's implementation with a mock that returns a predefined value within a context.

Communicative Purpose

Express a testing scenario where a method's return value is controlled to isolate the unit under test.

Pattern

with patch.object(<Class>, '<method>', return_value=<value>):

Core Structure

with patch.object(<Class>, '<method>', return_value=<value>):

Função primária

Temporarily replace a method's implementation with a mock that returns a predefined value within a context.

Propósito comunicativo

Express a testing scenario where a method's return value is controlled to isolate the unit under test.

Situações de gatilho

When writing unit tests where a method's side effects or return value must be controlled to isolate the unit under test.

Contextos

Unit testing with Python's unittest.mock, test doubles, mocking dependencies.

Padrão

with patch.object(<Class>, '<method>', return_value=<value>):

Estrutura central

with patch.object(<Class>, '<method>', return_value=<value>):

Slots de substituição

Class: any class name; method: any method name (string); value: any return value (literal or expression)

Colocados típicos

  • unittest.mock.patch
  • MagicMock
  • assert_called_with
  • test case
  • pytest

Substituições comuns

  • patch.object(target
  • attribute
  • return_value=value) can be replaced with patch.object(target
  • attribute
  • return_value=lambda *args
  • **kwargs: value) or using side_effect.

Erros comuns

1. Forgetting to stop the patch (cause: using patch without context manager or decorator; consequence: mock persists beyond test, affecting other tests). 2. Patching the wrong attribute (cause: typo in method name; consequence: AttributeError or mocking wrong method). 3. Assuming the mock replaces the class attribute instead of the instance method (cause: patching class vs instance; consequence: mock not applied as expected). 4. Using return_value with a mutable default that mutates across tests (cause: mutable default; consequence: test pollution). 5. Neglecting to assert that the mocked method was called (cause: missing assertion; consequence: false positives).

Similar / contraste

patch.object vs patch: patch.object targets a specific attribute on an object/class; patch targets a name in a module. | patch.object vs MagicMock: patch.object replaces an attribute; MagicMock creates a mock object that can be assigned manually. | unittest.mock vs unittest.mock.mock: the former is the public API; the latter is internal.

Interferências

Coming from Java: may expect Mockito's when(...).thenReturn() syntax; in Python, use patch.object with return_value. | Coming from JavaScript: may expect jest.fn().mockReturnValue(); in Python, use patch.object or MagicMock. | Coming from Ruby: may expect RSpec's allow(object).to receive(:method).and_return(value); in Python, use patch.object.

Família do chunk

  • unittest.mock.patch
  • MagicMock
  • test double
  • mocking

Nuance

Do not use when the method has side effects that must be preserved; prefer side_effect or real implementation. Performance impact is minimal as patching is lightweight but adds overhead per test. Boundary: patching works on attributes accessible via attribute access; descriptors, properties, or class methods may require different handling.

Efeito pragmático

Enables isolated unit tests by eliminating external dependencies and controlling method outputs, leading to faster, more reliable test suites.

Dica de memória

Think of patch.object as a temporary stunt double that steps in for a method's performance, then steps out when the scene ends.

Upgrade path

Consider using patch.object with side_effect for dynamic responses or patch.multiple to mock several attributes at once.

Tipo de construção: routineTag de espaçamento: Medium-term

Log in to save chunks.