How to mock in Python with ease?

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.

Software Engineer, LL.B., MSc in CS

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

ReInventing static sites with AWS

5 steps how a QA can go through onboarding on a new project taking care of himself.

CS373 Spring 2022: Michael Tran: Final Entry

How to build a network scanning analysis platform — Part II

Top 2 Open Source and Commercial RPA Tools

‘Dirty Pipe’ Linux Kernel Privilege Escalation Vulnerability (CVE-2022–0847)

Day One: Makers Academy — And We’re Live!

How To Limit Battery Charging (Set A Charge Threshold) For ASUS Laptops On Linux

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vladyslav Krylasov

Vladyslav Krylasov

Software Engineer, LL.B., MSc in CS

More from Medium

Python: Logging from multiple modules

How to convert data in python format to data in JSON format?

What are Environment Variables?

For loop example with explanation using Java