Member-only story
Pytest Mocking Cheat Sheet
Mocking made simple, patching made easy
The previous article I wrote, which received over 100K views on Medium, provided a broad overview of pytest
, covering topics on the setup, execution, and advanced features such as marking, mocking, and fixture usage. To quote from the previous article,
Mocking is used in unit tests to replace the return value of a function. It is useful to replace operations that should not be run in a testing environment, for instance, to replace operations that connect to a database and load data when the testing environment does not have the same data access.
There is so much more to the topic of mocking. This article will show examples of how to mock constants, functions, an initialized instance of a class, private methods, magic methods, environment variables, external modules, fixtures, and even user inputs! Since mocking replaces actual values with inserted “fake” values, this article will also touch on meaningful assertions to use hand-in-hand with mocking.