我需要测试一个使用大量我现在无法触及的遗留代码的函数。我在测试类上使用
LegacyClass
装饰器修补了遗留类 (@patch
)。遗留类有一个方法 get_dict(args)
返回一个字典,出于测试目的,我需要用静态字典模拟 get_dict(args)
的返回。
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
测试.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}})
#heare I call the function that I need to test, that uses the LegacyClass
在我的函数中,我使用返回的
dict
来检查是否存在特定的 value
,否则我返回默认值。即使预期值为 1
,如上例所示,该函数也会返回默认值。看来get_dict
的模拟不起作用或者我做错了什么。
这是一个例子:
$ tree
# output:
├── src
│ ├── __init__.py
│ ├── my_module.py
├── test_example.py
src/my_module.py:
class LegacyClass:
def get_dict(self) -> dict:
return {}
test_example.py:
from unittest import TestCase, mock
from src.my_module import LegacyClass
class TestExample(TestCase):
def test_mock(self):
legacy_instance = LegacyClass()
# before mock result is empty dict
self.assertDictEqual({}, legacy_instance.get_dict())
with mock.patch(
'src.my_module.LegacyClass.get_dict',
return_value={'data': {'value': 1}},
):
mocked_result = legacy_instance.get_dict()
self.assertDictEqual(mocked_result, {'data': {'value': 1}})
让我们检查一下:
pytest test_example.py
============================================================================================= test session starts =============================================================================================
...
collected 1 item
test_example.py . [100%]
============================================================================================== 1 passed in 0.03s ==============================================================================================