Lazy Attributes and Methods
What you want to be able to do is just mock the bits and pieces of it that you use in your program. Fortunately, you don’t have to do that. The
Mock objects are super flexible and they actually create methods and attributes when you access them. So, as you’ve seen, when we printed out the
dir() representation of
json—which is now a
Mock object—it doesn’t have the
And that’s interesting—we actually get another
Mock object. What happened here is that we called this
.dumps() method, which didn’t exist, and when we called it, it actually created another
So obviously, this isn’t really the true
.dumps() method, and we can verify that by even deleting the arguments. So, the regular
json.dumps() requires some arguments but if we save this and we call
json.dumps() with no arguments, we run our program again—we’ll see that it still returns a
Mock object and it doesn’t raise an exception or cause any error.
So the fact that when you create a method like
.dumps() from a
Mock object it will return another
Mock object and it will accept any arguments that you pass to it—this feature of
Mock objects is what allows a lot of flexibility and the ability to create more control and testing. And in the next video, we’re going to explore this idea some more.
Become a Member to join the conversation.