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.
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 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.