如何在unittest中断言在try except块中捕获的异常?



在我的生产函数中:

def myfunction():
try:
do_stuff()
(...)
raise MyException("...")
except MyException as exception:
do_clean_up(exception)

我的测试失败了,因为在try/except块

中捕获了异常
def test_raise(self):
with self.assertRaises(MyException):
myfunction()

自我。assertRaises永远不会被调用。

如何保证在测试期间捕获异常?

永远不会断言异常AssertionError: MyException not raised

这是因为您直接在myFunction()中捕获了异常MyException

注释掉try-except子句,再试一次,测试应该通过。

assertRaises用于未捕获的错误。你也可以在except块中重新引发。

异常在内部处理,因此没有外部证据表明异常被引发。

然而,MyExceptiondo_clean_up都是外部名称,这意味着您可以修补它们并断言它们是否被使用。例如,

# Make sure the names you are patching are correct
with unittest.mock.patch('MyException', wraps=MyException) as mock_exc, 
unittest.mock.patch('do_clean_up', wraps=do_clean_up) as mock_cleanup:
myfunction()
if mock_exc.called:
mock_cleanup.assert_called()

最新更新