
Test & Code 145: For Those About to Mock - Michael Foord
Feb 18, 2021
In this engaging discussion, Michael Foord, the creator of unittest.mock and a seasoned Python testing expert, dives into the art of mocking in Python. He shares insights on testing philosophy, emphasizing behavior over implementation. Michael explains his inspirations for unittest.mock and the nuances of patching, mocking external dependencies, and designing for testability. He also debates the merits of unittest versus pytest, offering practical tips and advocating for clear team roles in testing as he encourages a hands-on approach to software quality.
AI Snips
Chapters
Transcript
Episode notes
Replacing Hundreds Of Handwritten Stubs
- Michael Foord described building mock objects to replace hundreds of hand-written test stubs at Resolver Systems early in his career.
- He implemented a 30-line dynamic object and added spec enforcement to avoid invalid attribute access.
Test The Unit Of Behavior
- Test the unit of behavior, not the unit of implementation, by using the public API for tests.
- Good end-to-end tests let you refactor internals without breaking tests that verify behavior.
Scope Mocks With Patch
- Use unittest.mock.patch as a context manager or decorator to inject and automatically restore mocks.
- Limit a patch's scope so state returns to normal after the test finishes.

