How to mock in Python with ease?

Vladyslav Krylasov
1 min readApr 11, 2020


Photo by Nick Night on Unsplash

Using of Python mock.patch makes you feel uncomfortable and a bit nervous? Afraid no more. I will describe in this article simple ways of doing so by asking yourself questions. See this repo to understand better what happens:

Q: I want to mock a method of an instance. How can I do it?
A: You need make use of return_value of Mock class.

Q: I want to mock an imported function. Ideas?
A: I was caught by this several times and it may more tricky than you might expect. If you imported something like datetime.datetime in your module there is a temptation to write something like this: mock.patch("datatime.datetime") but it won’t work and you need to do mock datetime in your module, i.e. mock.patch("x.datetime") .

Q: I want to mock a module. How can I achieve it?
A: this one won’t be a big headache for you. Do something like this.

P.S. One side note if you want to mock a package i.e. import datetime then it works similarly to the mocking of a function.

Hope it was helpful.