PyCon UK 2019

Mock Object Library: Common Pitfalls and Best Practices
2019-09-15, 14:30–15:00, Room D

This talk is an introduction to the mock object library along with a detailed discussion on common pitfalls associated with patching objects with mocks and the best practices for it. The talk would include code examples and stories from real projects to demonstrate how to use mocks effectively.


Unit testing is an integral part of any matured software development process. Python comes with the unittest package that provides a very comprehensive unit testing framework for writing unit tests. Often, the functionality being tested depends on complex external objects that are unnecessary and/or impractical to create in unit tests. That's when we need to use mock objects to partially simulate the behaviour of the external objects in order to write the unit tests and invoke the functionality being tested. Sometimes we also need to validate whether the functionality being tested exercised the mock objects in certain ways. Python comes with a quite comprehensive mock object library in the form of unittest.mock module that fulfills these requirements of mocking objects.

This talk would discuss how to use the unittest.mock library to create mock objects, patch modules and classes, record method calls on mock objects, and make assertions about which mock methods or attributes are exercised during tests, the number of times they are called, and the arguments they are called with. Additionally, this talk would also discuss how to construct complex mock objects that simulate specific expected behaviour such as returning specific values, returning different values on different calls, possessing certain attributes, triggering side effects such as raising exceptions, etc.

Further, this talk would dive into common pitfalls that one encounters while using unittest.mock, e.g., how mocking a builtin function could cause unexpected errors and how to work around them. These examples are drawn from the speaker's experience while working on Python projects.

The goal of this talk is to help Python developers with a basic knowledge of unit testing to effectively use mock objects in order to write better, simpler, and robust unit tests.


Is your proposal suitable for beginners? – True