Mock vs MagicMock
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Introduction
Mock and MagicMock are classes in Python's unittest.mock library for creating test doubles. MagicMock is a subclass of Mock that automatically provides default implementations for all magic (dunder) methods like __len__, __iter__, __getitem__, and __str__. Use MagicMock by default because it works in more situations. Use Mock when you need to prevent magic method calls from silently succeeding (e.g., to catch accidental use of len() or iteration on a mock).
Mock Basics
Mock creates an object that records all calls and attribute accesses:
MagicMock Extras
MagicMock adds automatic support for magic methods:
Key Differences
When to Use Each
Use MagicMock (Default Choice)
Use Mock (When You Want Strictness)
Configuring Magic Methods
Common Patterns
Mocking a Database Repository
Using spec for Safety
side_effect for Dynamic Returns
Common Pitfalls
- Using
Mockwhen the code useslen(),in, or iteration:MockraisesTypeErrorfor magic methods. If the code under test callslen(mock)or iterates over the mock, useMagicMockinstead. - Forgetting that
MagicMocksilently accepts all magic method calls:MagicMock.__len__()returns0by default instead of raising an error. This can mask bugs where magic methods are called unexpectedly. UseMockwithspecfor stricter behavior. - Not using
specto restrict mock attributes: Withoutspec, bothMockandMagicMockaccept any attribute access or method call. Typos likemock.gett_user()silently succeed. Usespec=RealClassto catch these errors. - Confusing
return_valuewithside_effect:return_valuesets a static return value.side_effectcan be a function, an iterable of values, or an exception. Setting both meansside_effecttakes precedence. - Asserting calls in the wrong order:
assert_called_with()only checks the most recent call. Useassert_any_call()to check if a call was made at any point, orcall_args_listto verify the complete call sequence.
Summary
MagicMockextendsMockwith default implementations for all magic methods (__len__,__iter__,__getitem__, etc.)- Use
MagicMockby default — it works in more situations and is the standard choice - Use
Mockwhen you want magic method calls to raiseTypeError(stricter testing) - Add
spec=RealClassto either class to restrict the mock to only the real class's interface - Configure magic methods with
mock.__len__.return_value = 5for custom behavior
Related reading
- Mocking a class Mock or patch?
- Mocking python function based on input arguments
- Modeling a graph in Python
- Models passed to fit can only have training and the first argument in call as positional arguments, found
- Mocking a function to raise an Exception to test an except block
- Mocking generic methods in Moq without specifying T
- Modifying a subset of rows in a pandas dataframe
- Modifying local variable from inside lambda
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.