Nei*_*ais 6 python unit-testing mocking
我正在使用Python模拟模块进行测试.我想监视由活动对象进行的内部方法调用.我发现'wraps'kwarg可用于设置一个模拟,该模拟侦测对活动对象的方法调用:
但这不适用于内部呼叫.我想用它来测试更高级别的方法以正确的顺序调用低级方法.
鉴于:
class ClassUnderTest(object):
def lower_1(self):
print 'lower_1'
def lower_2(self):
print 'lower_2'
def higher(self):
self.lower_1()
self.lower_2()
Run Code Online (Sandbox Code Playgroud)
我想能够测试它
import mock
DUT = ClassUnderTest()
mock_DUT = mock.Mock(wraps=DUT)
# test call
mock_DUT.higher()
# Assert that lower_1 was called before lower_2
assert mock_DUT.mock_calls[1:] = [mock.call.lower_1(), mock.call.lower_2()]
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为'self'参数更高()绑定到原始DUT对象,而不是mock_DUT间谍.因此,只有初始的high()调用被记录到mock_calls.有没有一种方便的方法来使用python mock模块执行这种断言?
这有点像在Java中使用Mockito间谍.http://docs.mockito.googlecode.com/hg/latest/org/mockito/Spy.html
你可以使用Mock(spec = obj)构造函数构造一个"间谍",它将使该__class__
属性等于ClassUnderTest,其中Mock(wraps = obj)构造函数不会.因为在python类方法中,将一个类实例self参数作为它们的第一个参数,你可以用mock来调用它,就像它是类上的静态方法一样.
import mock
DUT = ClassUnderTest()
spy = mock.Mock(spec=DUT)
# test call
ClassUnderTest.higher(spy)
# Assert that lower_1 was called before lower_2
assert spy.mock_calls == [mock.call.lower_1(), mock.call.lower_2()]
Run Code Online (Sandbox Code Playgroud)