I have a function which uses 2 instances of the same class and I want to test that function using python mock. But I'm breaking my head how I can mock this. I already used my friends Google and Stackoverflow to find a solution but until now did not find any.
As simple mock-example which shows the principle of what I want to test:
class MyClass(object): # this class is inside a module I'm not allowed to change.
def __init__(self, name, value):
self._name = name
self._value = value
def get_value(self):
return self._value
And then the module-under-test (again a mock-implementation to show the idea):
import my_class_module
def my_function():
a = my_class_module.MyClass('a', 3)
b = my_class_module.MyClass('b', 4)
return a.get_value() + b.get_value()
The global idea for the unittest of my_function I have in mind is as follows (but this idea is currently not working of course):
mock.patch('module.my_class_module.MyClass')
def test_my_function(self, mock_my_class):
def _my_get_value(self): # ideally I would like to use get_value.return_value per instance, but I don't know how.
if self._name == 'a':
return 4 # Different values to make sure that we can verify that the mock is called
else:
return 5
# Next line is the one I'm wondering about since mock_myh_class.return_value should differ for each instance.
# But again this next line is already a work-around idea, since I don't know how to set the return-value of get_value for each instance.
mock_my_class.return_value.get_value.side_effect = my_get_value
exp_result = 9
result = module.my_function()
self.assertEqual(result, exp_result)
What am I missing to make this work? Aka: how can I mock 2 instances of the same class?