在引发多个异常的测试用例中使用assertRaises()

2024-06-28 14:47:42 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以将AssertRails与多种类型的异常一起使用。像这样的东西

assertRaises(RuntimeError, "error message")
assertRaises(Exception, "exception message")

这两个错误都发生在同一个调用的不同位置。在

我怎样写一个单独的资产负债表来处理这两者。在

正如您可以想象的那样,当只提到一个执行时,单元测试用例就会失败。在


Tags: message错误exception测试用例error资产单元想象
1条回答
网友
1楼 · 发布于 2024-06-28 14:47:42

直接从docs开始:

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.

所以,你的代码应该看起来像

assertRaises((RuntimeError, IndexError), "error message")

相关问题 更多 >