假设我想确保正确调度某些标志等,以便在我的库深处调用特定函数:high_order_function_call(**kwargs)
深处包含library_function_call()
我想确保它被实际调用。
为此给出的典型示例使用 mock.patch
:
@mock.patch('library')
def test_that_stuff_gets_called(self, mock_library):
high_order_function_call(some_example_keyword='foo')
mock_library.library_function_call.assert_called_with(42)
现在在这种情况下,我必须等待
high_order_function_call
中所有内容的完整执行.如果我想立即停止执行并跳回我的单元测试怎么办 mock_library.library_function_call
达到了吗?
最佳答案
您可以尝试在调用中使用引发副作用的异常,然后在测试中捕获该异常。
from mock import Mock, patch
import os.path
class CallException(Exception):
pass
m = Mock(side_effect=CallException('Function called!'))
def caller_test():
os.path.curdir()
raise RuntimeError("This should not be called!")
@patch("os.path.curdir", m)
def test_called():
try:
os.path.curdir()
except CallException:
print "Called!"
return
assert "Exception not called!"
if __name__ == "__main__":
test_called()
关于Python unittest 和 mock : Check if a function gets called, 然后停止测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38381602/