我想要对功能进行单元测试
def function(self, timeout):
self.method1(self.method2(self.PARAM), timeout=timeout)
我目前的单元测试是
patcher = patch("x.x.x.method2")
method2_mock = patcher.start()
self.addCleanup(patcher.stop)
...
@patch("x.x.x.method1")
def test_function(self, method1_mock):
timeout = 1
self.method2_mock.return_value = "val"
self.page.function(timeout)
self.method2_mock.assert_called_once_with(self.page.PARAM)
method1_mock.assert_called_once_with("val", timeout=1)
运行测试时,我在测试的实际函数中的method1中出现以下错误:
Traceback (most recent call last):
File "~/.local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
...
File "~/.local/lib/python2.7/site-packages/mock/mock.py", line 1062, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "~/.local/lib/python2.7/site-packages/mock/mock.py", line 1128, in _mock_call
ret_val = effect(*args, **kwargs)
TypeError: local_side_effect() got an unexpected keyword argument 'timeout'
为什么我的模拟方法1不接受关键字参数以及如何解决问题?
答案 0 :(得分:0)
似乎我修补方法的方式对于这个问题至关重要。第一种方法,在设置中修补:
patcher = patch("x.x.x.method2")
method2_mock = patcher.start()
self.addCleanup(patcher.stop)
只允许我在模拟中使用assert
方法。
但是,使用
修补单个测试@patch("x.x.x.method1")
并将模拟作为参数传递给测试,我能够编辑return_value
等属性,如果被模拟,则可以编辑其子属性。在这种情况下,修复只是用
@patch("x.x.x.method2")
并将其传递给测试函数
def test_function(self, method1_mock, method2_mock):