引发多个异常的测试用例中的 assertRaises()
assertRaises() in a test cases that raises multiple exceptions
是否可以对多种类型的异常使用 assertRaises。像
这样的东西
assertRaises(RuntimeError, "error message")
assertRaises(Exception, "exception message")
这两个错误都发生在我的代码中不同位置的同一个调用。
如何编写一个 assertRaises 语句来处理这两个问题。
正如您想象的那样,当仅提及其中一个执行时,单元测试用例会失败。
直接来自 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")
是否可以对多种类型的异常使用 assertRaises。像
这样的东西assertRaises(RuntimeError, "error message")
assertRaises(Exception, "exception message")
这两个错误都发生在我的代码中不同位置的同一个调用。
如何编写一个 assertRaises 语句来处理这两个问题。
正如您想象的那样,当仅提及其中一个执行时,单元测试用例会失败。
直接来自 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")