Mock Objects
00:00
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
.
00:13
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.
00:27
Go down to your terminal and run your program. I called mine mock.py
.
00:33
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 Mock
object?
00:42
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.
01:20
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.
01:38
What you can do is use your Mock
object to patch this dependency. You could say json = mock
, and now json
is a Mock
object.
01:50
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 {'a': 1}
.
02:12
So 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 json
module,
02:30
but when I patch json
here, saying json = mock
, this mock
object doesn’t have a .dumps()
method associated with it.
02:39
And just to prove that, I’m going to go ahead and print the dir()
of json
.
02:46 Let’s go ahead and run this program again,
02:49
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.
03:01
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.