[有许多示例显示了如何断言已使用Mock调用的方法,例如。 assert_called_with()
,但所有这些都涉及用Mock实例替换该方法。
我想要的有点不同,我希望函数在不替换其主体的情况下正常执行,但是仍然想断言是否已调用该函数。
例如
def dosomething(...)
# creates records that I will test later on.
....
def execute():
....
dosomething()
在我的测试中
def test_a(...):
with patch(dosomething...) as mocked:
execute()
mocked.assert_called_with()
我知道我可以针对dosomething()
创建的记录进行测试。是的,我同意,但是我只是想确定是否有可能按照我的问题去做。
使用Mock
的wraps
kwarg并将其传递给原始方法。
例如,
>>> from unittest import mock
>>> def hi(name): print('hi', name)
>>> mock_hi = mock.Mock(wraps=hi)
包装的函数由模拟程序调用。
>>> mock_hi('Bob')
hi Bob
但是它仍然是可以记住呼叫的模拟。
>>> mock_hi.call_args_list
[call('Bob')]
回想一下patch()
将传递额外的kwargs到它产生的Mock
,因此您也可以在此处使用wraps
参数。例如,
>>> with mock.patch('builtins.float', wraps=float) as mock_float:
... x = float('inf')
... print(x) # If we hadn't wrapped, x would be a mock.
... print(mock_float.call_args_list)
...
inf
[call('inf')]