Python unittest 和 mock : Check if a function gets called, 然后停止测试

标签 python unit-testing mocking

假设我想确保正确调度某些标志等,以便在我的库深处调用特定函数:
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/

相关文章:

python - 合并 pandas df 中的值

python - 根据 Pandas 中的行值过滤列

java - 对调用多个私有(private)方法的公共(public)方法进行单元测试

javascript - Jasmine spy On调用原始函数

在类中使用的 python 模拟全局函数

python - Pandas 将一个值替换为指定列的另一个值

python - 无法 pickle 空的 ordered_set

python - 如果 `pandas.testing.assert_frame_equal` 失败,如何输出所有差异?

php - PHP中的单元测试数据存储

mocking - Rhino Mocks 上的模拟和 stub 之间有什么区别?