2

I want to patch get_age() method I have, based on the argument passed.

Let's say I have get_age.py where I am using multiple times the same get_age() method.

get_age("Anna")
...
get_age("Ben")

and then in test I want to do:

@patch('get_ages.get_age') <-- mock getting age of Ben
@patch('get_ages.get_age') <-- mock getting age of Anna
def test_get_ages(self, age_A, age_B):

How can I do the mocking of the same method based on the name passed? Thanks!

1 Answer 1

2

This can be achieved using the side_effect param to patch.object to call a function which returns a different result depending on the input. For example:

def find_ages(*args):
    if args[0] == 'Anna':
        # Return Anna's data
        return 18
    elif args[0] == ' Ben':
        # Return Ben's data
        return 45

@patch.object(get_ages, 'get_age', side_effect=find_ages)
def test_get_ages(self, get_age):
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.