【问题标题】:Mocking a method with keyword arguments使用关键字参数模拟方法
【发布时间】:2018-06-06 12:59:29
【问题描述】:

我要对函数进行单元测试

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 不接受关键字参数,我该如何解决这个问题?

【问题讨论】:

    标签: python python-2.7 mocking python-unittest keyword-argument


    【解决方案1】:

    看来我修补方法的方式对问题至关重要。第一种方式,在设置中打补丁:

    patcher = patch("x.x.x.method2")
    method2_mock = patcher.start()
    self.addCleanup(patcher.stop)
    

    只允许我在模拟上使用assert 方法。

    但是,为单个测试打补丁

    @patch("x.x.x.method1")
    

    并将模拟作为参数传递给测试,我可以编辑return_value 等属性,如果被模拟,则可以编辑其子属性。在这种情况下,修复只是简单地用

    修补方法2
    @patch("x.x.x.method2")
    

    并将其传递给测试函数

    def test_function(self, method1_mock, method2_mock):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 2015-10-24
      相关资源
      最近更新 更多