Meaning
Creates a mock object that auto-generates attributes and methods on access, serving as a configurable test double. Addresses the need to isolate units under test from their real dependencies without implementing actual behavior. Triggered when writing unit tests that require a stand-in for a collaborator or external service.
Primary Function
Testing
Communicative Purpose
Enables isolation of code under test by substituting real dependencies with configurable mock objects.
Pattern
mock = MagicMock()
Core Structure
... = MagicMock()
Função primária
Testing
Propósito comunicativo
Enables isolation of code under test by substituting real dependencies with configurable mock objects.
Situações de gatilho
Unit testing: isolating a function from its database layer; API testing: simulating external service responses without network calls; Error path testing: configuring a mock to raise an exception
Contextos
unittest.mock, pytest, Django test framework, Flask testing
Padrão
mock = MagicMock()
Estrutura central
... = MagicMock()
Slots de substituição
mock: variable name for the mock object instance
Colocados típicos
- patch()
- Mock
- return_value
- side_effect
- assert_called_with
- call_args
Substituições comuns
- Mock() — no auto-created magic methods
- lighter weight
- create_autospec() — enforces real object API signature
- patch() — replaces objects at module level via context manager
Erros comuns
Forgetting parentheses: mock = MagicMock assigns the class itself, not an instance — leads to AttributeError when accessing mock attributes Not setting return_value: mock methods return another MagicMock by default, which can mask bugs where real return types matter Over-mocking: replacing too many dependencies creates brittle tests disconnected from real integration behavior Accessing a typo attribute silently succeeds instead of failing — MagicMock auto-creates any attribute on access
Similar / contraste
Mock (base mock without pre-created magic methods), patch (module-level object replacement), create_autospec (spec-enforced mock that raises on invalid attributes)
Interferências
Coming from JavaScript/Jest: may expect jest.fn() auto-recording and jest.mock() hoisting — Python's MagicMock does not hoist and uses different assertion syntax Coming from Ruby/RSpec: may expect doubles to raise on unexpected method calls — MagicMock auto-creates child mocks instead of failing Coming from Java/Mockito: may look for when().thenReturn() syntax — Python uses return_value and side_effect assignment instead
Família do chunk
- Mock()
- patch()
- call()
- create_autospec()
- ANY
Nuance
Do not use MagicMock when you need the mock to enforce the real object's API — use create_autospec instead. MagicMock instances are lazy: any attribute access creates a new child mock, which can mask typos and incorrect usage. Passing spec= limits the mock to a real object's interface while retaining MagicMock flexibility.
Efeito pragmático
Prevents test failures caused by real dependency side effects and enables fast, deterministic, isolated test suites.
Dica de memória
MagicMock is a shape-shifter — ask it for any attribute or method and it materializes one on the spot, like a genie granting wishes you didn't know you had.
Nota
MagicMock is a subclass of Mock that pre-creates magic methods like my_mock = MagicMockstrmy_mock = MagicMock, my_mock = MagicMocklenmy_mock = MagicMock, my_mock = MagicMockitermy_mock = MagicMock, making it suitable for mocking objects that participate in Python protocols.
Upgrade path
create_autospec() for spec-enforced mocks, patch() as context manager or decorator for module-level replacement
Log in to save chunks.