I recently write some unit tests by using unittest.mock module to mock objects/methods. patch is a very handy tool to use. However, it is not so obvious to use at the beginning.

Mock a method

Solution 1 is easy to understand, which uses a method to replace requests.get.

Solution 2 generates an instance of MagicMock (default), which has an attribute return_value as the return value of its function call.

Mock the attribute of an instance

However, when the return value is an instance of a class, which has some attributes. How should we mock it?

In doing so, we can mock the attribute of an instance.

Mock instances generated by nested factory methods

A more complex case would be as follows:

As you can see, resource() generates a Resource instance and Resource.Table() creates a Table instance. So if we would like to mock the Table instance, we need to mock the return_value twice.

The unittest.mock has more features to explore, but so far the above three patching solutions can make my writing of a unit test much easier.