mock = MagicMock
Testing Patterns

Meaning

Creates a configurable mock callable whose return_value attribute determines what the mock returns each time it is invoked. Addresses the need to stub dependencies with deterministic outputs during unit testing. Reached for whenever a test requires a collaborator to produce a known, repeatable value without executing real logic.

Primary Function

Provides a mock callable that returns a fixed value for use in unit tests.

Communicative Purpose

Indicates that a dependency should be stubbed to return a specific constant during testing.

Pattern

MagicMock(return_value=value)

Core Structure

MagicMock(return_value=...)

Função primária

Provides a mock callable that returns a fixed value for use in unit tests.

Propósito comunicativo

Indicates that a dependency should be stubbed to return a specific constant during testing.

Situações de gatilho

When a function or method under test calls a collaborator that should return a known constant value, allowing the test to isolate the unit under test.

Contextos

Unit testing with Python's unittest.mock framework, especially when stubbing functions, methods, or objects that return a constant.

Padrão

MagicMock(return_value=value)

Estrutura central

MagicMock(return_value=...)

Slots de substituição

value: any Python object

Colocados típicos

  • MagicMock
  • patch
  • patch.object
  • return_value
  • side_effect

Substituições comuns

  • return_value can be any object (e.g.
  • None
  • True
  • False
  • list
  • dict
  • another mock)
  • side_effect can be used instead for dynamic behavior.

Erros comuns

Confusing return_value with side_effect – cause: misunderstanding the purpose of each argument; consequence: mock returns unexpected values or raises AttributeError. Forgetting to call the mock (checking mock.return_value instead of mock()) – cause: treating the mock as a value rather than a callable; consequence: test may pass incorrectly or fail to detect missing calls. Over‑mocking leading to brittle tests – cause: mocking too many dependencies or irrelevant methods; consequence: tests become tightly coupled to implementation details and break on refactoring.

Similar / contraste

Similar to MagicMock(side_effect=lambda *args: 42) – provides dynamic return values per call; contrasted with MagicMock() – returns a new mock on each attribute access instead of a fixed constant.

Interferências

Coming from JavaScript/Jest: may write jest.fn().mockReturnValue(value) instead of MagicMock(return_value=value) → Use MagicMock(return_value=value) as a constructor argument. Coming from Java/Mockito: may expect when(mock.method()).thenReturn(value) chaining → Configure return_value directly on the mock object.

Família do chunk

  • python-mock-patterns

Nuance

1) Do not use when the collaborator's return value must vary based on input or state; 2) Using return_value adds negligible overhead, but excessive mocking can increase test fragility and slow test suites due to many mock objects; 3) Attribute access on the mock returns new mocks unless explicitly configured, which can cause unexpected AttributeError if attributes are accessed unintentionally.

Efeito pragmático

Signals to readers of the test that the mocked dependency is expected to be invoked and to produce a known constant, clarifying the test's assumptions.

Dica de memória

Think 'mock returns 42' as a quick way to stub a function that should yield a known answer.

Nota

Commonly used in unit tests to isolate the unit under test from external dependencies by providing a deterministic return value.

Upgrade path

Consider using side_effect for more complex return behaviors or employing patch to automatically clean up mocks after the test.

Frequência: HighFormulaicidade: Semi-fixedTipo de construção: Object instantiation using MagicMock with the return_value keyword argument.Prioridade de aquisição: Active recallPrioridade de output: OutputTag de espaçamento: Short-term

Log in to save chunks.