【发布时间】:2012-01-01 02:52:10
【问题描述】:
我正在将mock 与 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)
方法二:使用patch创建mock。代码如下:
@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)
这两种方法都做同样的事情。我不确定这些差异。
有人能告诉我吗?
【问题讨论】:
-
作为一个从未尝试过Mock()或patch的人,我觉得第一个版本更清晰,并且显示了你想要做什么,尽管我不了解实际的区别。我不知道这是否有任何帮助,但我认为传达一个外行程序员的感受可能会很有用。
-
@MichaelBrennan:感谢您的评论。确实有用。
标签: python unit-testing mocking