All right, so let’s go ahead and get started creating and exploring mock objects. First, we need to import the mock library, so
from unittest.mock import Mock.
This will give you the
Mock class, which you can make your mock objects from. I’m going to say
mock = Mock(), and then let’s just
print(mock) so we can see what this
Mock object looks like.
Go down to your terminal and run your program. I called mine
You’ll see a representation of the
Mock object that has this
id, which is a string of numbers. What do we do with this
Like, how do we use it? Well, you’ll learn more about the methods of the
Mock object in upcoming videos, but the way that
Mock objects are generally used is to patch other objects in your code. When I say patch, I just mean replace, imitate, mock—they’re all kind of the same word in this context.
01:02 Now, remember the essence of mocking is to imitate something as close to the real thing as possible. And also remember that when you’re running your tests, you want it to be in a controlled environment so external dependencies don’t make your tests fail.
For example, let’s say you have an external dependency that you import in your program. Say you do, like,
import—and I’ll use
json as an example, but pretend this is like some external dependency that is hard to control and has behavior that you don’t necessarily want to happen in your tests.
What you can do is use your
Mock object to patch this dependency. You could say
json = mock, and now
json is a
But this isn’t really good enough because when you have an external dependency, you probably use properties and methods associated with it. For example, with
json I might say
data = json.dumps() of some dictionary
json.dumps() just takes a Python dictionary and it dumps it, dump-s, a string representation of it into some variable. So I’m just using a method from this external dependency of the
but when I patch
json here, saying
json = mock, this
mock object doesn’t have a
.dumps() method associated with it.
And just to prove that, I’m going to go ahead and print the
02:46 Let’s go ahead and run this program again,
and we’re seeing this list of strings, and these are methods associated with the
Mock object. And notice how
.dumps() is not one of the methods here.
But I want to mock this external dependency, so I want my
mock object to have a
.dumps() method too. So next, you’re going to learn how
Mock objects handle this problem of imitating an external dependency and all of its methods and properties associated with it.
Become a Member to join the conversation.