I need to test a function that uses a lot of legacy code that I can't touch now. I patched the legacy class (LegacyClass) with the @patch decorator on my test class. The legacy class has a method get_dict(args) that returns a dictionary and for my test purpose I need to mock the return of get_dict(args) with a static dictionary.
class_to_test.py
from my_module import LegacyClass
class ClassToTest():
self.legacy=LegacyClass() #I can't touch this part noe
def method_to_test(self):
d = self.legacy.get_dict()
if d['data']['value'] == 1:
return True
else:
return None
test.py
@patch('my_module.LegacyClass')
class TestClass(unittest.TestCase):
def test_case(self, legacy_mock):
legacy_mock.get_dict = MagicMock(return_value={'data': {'value': 1}})
ctt = ClassToTest()
assert ctt.method_to_test()
In my function, I use the returned dict to check if a specific value is present otherwise I return a default value. The function returns the default value even if the expected value is 1 as in the above example. It seems that the mock of get_dict doesn't work or I do something wrong.
Updated
Here is an example:
src/my_module.py:
src/class_to_test.py:
test_example.py:
Let's check: