Imagine you have the following code
def do_something():
users = User.objects.filter(dob__gte='1980-01-01')
for user in users:
# do something to user
If you were writing unit test against do_something()
, you would need to do some complex mocking on User.objects.filter()
to return some mock up data.
But this can be easily prevented by refactoring into a separate get_users()
method as below:
def get_users():
return User.objects.filter(dob__gte='1980-01-01')
def do_something():
users = get_users()
for user in users:
# do something to user
This way, you can just mock get_users()
to return the mock data.