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

Host Your First Blog Here. This is For Absolute Beginners

Presearch: Earn Crypto For Searching the Internet

Creating Organizational Units, Security Groups, Shared Folders

Attending my First Bootcamp

Coding On My Phone

Become The Shortcut Master — Chrome and Atom (Part 2)

CAD Berry is Done!! (ish)

Your first Swift Application — without a Mac

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

GET requests with Python, ORDS, and the Oracle Autonomous Database

Objects in SQL Worksheet in Oracle Autonomous Database, Chris Hoina, Senior Product Manager, ORDS, Database Tools,

Two styles in Python to execute a command.

Python’s urllib. request for HTTP Requests

Creating and Promoting Python PyPI Libraries