Danny
Danny

Reputation: 161

python mock a function with different argument and assert with return values

This may be a simple question, but I'm new to mock testing, and cant get my head around on how to make this work.

I have a code like this

def check_item(item):
    <do some processing>
    return processed_item

Basically I'm trying to mock this function with multiple items, and respective return values. for example, if item is apple return value is processed_apple, if its an orange, returned value is processed_orange etc.

So far, I'm trying to write a test case, and stuck with the below

import my_module
from unittest.mock import patch

@patch("my_module.check_item")
def test_check_item(self, check_item):
    check_item.assert_called_once_with("apple")
    check_item.return_value = 'processed_apple'

Not sure, If Im doing right (or the correct way). And how can I check multiple arguments with different set of return value for each arguments?

Upvotes: 1

Views: 1604

Answers (1)

Farhad
Farhad

Reputation: 752

To test is the method was called or not:

check_item.assert_called_once_with("apple")

You should first call the function:

@patch("my_module.check_item")
def test_check_item(self, check_item):
   check_item("apple")
   check_item.assert_called_once_with("apple")
   check_item.return_value = 'processed_apple'

But in the code I do not see any reason to test it like that, Because it is just testing the mock module.

If you want to test the function return values, you should not mock the function but leave as it is and just test for the different scenarios. For example:

def test_check_item(self):
   result = check_item("apple")
   self.assertEqual(result, "some predefined result")

The purpose of unit testing is to test the method/class for correct behavior

Upvotes: 1

Related Questions