我正在使用Python的模拟,并想知道这两种方法中的哪一种更好(阅读:更多pythonic).
方法一:只需创建一个模拟对象并使用它.代码如下:
def test_one (self):
mock = Mock()
mock.method.return_value = True
self.sut.something(mock) # This should called mock.method and checks the result.
self.assertTrue(mock.method.called)
Run Code Online (Sandbox Code Playgroud)
方法二:使用补丁创建模拟.代码如下:
@patch("MyClass")
def test_two (self, mock):
instance = mock.return_value
instance.method.return_value = True
self.sut.something(instance) # This should called mock.method and checks the result.
self.assertTrue(instance.method.called)
Run Code Online (Sandbox Code Playgroud)
两种方法都做同样的事情.我不确定这些差异.
谁能开导我?
假设我在Python单元测试中有以下代码:
aw = aps.Request("nv1")
aw2 = aps.Request("nv2", aw)
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的方法可以断言aw.Clear()在测试的第二行中调用了一个特定的方法(在我的例子中)?例如,有这样的事情:
#pseudocode:
assertMethodIsCalled(aw.Clear, lambda: aps.Request("nv2", aw))
Run Code Online (Sandbox Code Playgroud)