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.
- Purpose of Mocking
- Mocking Packages
- Implementations
- Assertions for Mocking
- Tips and Tricks
- Examples (mock constants, function, class, and more)
Why mock and what should you mock?
Instead of listing the instances where you should implement mocking, it will be more intuitive to understand the purpose of unit tests and the use cases of mocking will naturally follow. Unit tests should be
- Independent: It should test the function and not its dependencies. With this consideration, the interface and wrappers should be tested, and external packages should be mocked if necessary
- Fast: Long-running functions or API calls can be mocked if they are not the subject of interest, especially if they also violate…