9

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.

physicist
  • 844
  • 1
  • 12
  • 24
  • 2
    It suggests to me that there is too much code within the test method, and this should be split to 2 different tests. – wim Sep 17 '18 at 20:24
  • 1
    This doesn't really make sense. A single call can only result in one single exception, because when it is raised the code will exit. – Daniel Roseman Sep 17 '18 at 20:25
  • A catch block can catch multiple exceptions but logically only exception would be raised and during testing that would be tested. – mad_ Sep 17 '18 at 20:28
  • @wim the flow tested by the case can cause error at two different places, so if one is caught the other can still come from the other point. I think these situations are common. – physicist Sep 17 '18 at 22:32
  • [This answer](https://stackoverflow.com/a/35490983/4288043) with a context manager is useful. – cardamom Sep 12 '19 at 14:14

1 Answers1

13

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")
DeepSpace
  • 78,697
  • 11
  • 109
  • 154