Return Value (Part 1)
00:00 One of the main reasons of using mock objects is to control the behavior of your code during tests. And one way to do this is to control the return value of a function, whether it’s one of your own or one of your dependencies.
Let’s look at an example of how we can control the return value of a function. Create a new file. I called mine
calendar.py. And we’re going to import
from datetime import datetime.
It’s not really relevant or important in this course about mocks to learn about the
datetime package, which is a whole other video course in itself, but we’re going to use one or two of these methods to help us explore this idea of changing the return value of a function.
Create a method called
is_weekday(), and this is just going to basically tell us if today is a weekday or not. Let’s say
today = datetime.today() and for exploratory purposes, let’s just go ahead and print
run the program again, and today is
6, which is Sunday, and yeah—it is actually Sunday where I am right now. So the purpose of this method is to return
True if today is a weekday and
False if it’s a weekend today.
It is Sunday today, so I expect this to be
False. I’m going to clear the screen and run the
calendar.py and it’s
False. Yours might return
True depending on what day of the week you’re writing this program. Cool.
Let’s write a test for
is_weekday(), so instead of printing it I’m just going to say
assert is_weekday(). Save that and run
calendar.py again, and we get an
is_weekday() is returning
False because today is Sunday. Again, your results may be different. When you’re writing tests, you want the results to be predictable.
03:16 Whether it’s a weekend or a weekday, we want our results to be the same every time we run our tests. And that’s really important, especially when you’re using something like continuous integration and continuous delivery—you don’t want your test to fail just because today is Sunday. In the next video, we’ll look at how we can use mocks to set the return value of this function.
Become a Member to join the conversation.