assertRaises() in a test cases that raises multiple exceptions

6.8k views Asked by At

Is it possible to use assertRaises with multiple types of exceptions. Some thing like

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

both these errors occur in my code at different places with the same call.

How can I write a singel assertRaises statement to handle both.

As you can imagine the unit test case fails when only one of the execptions is mentioned.

1

There are 1 answers

0
DeepSpace On BEST ANSWER

Straight from the 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.

So, your code should look like

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