assertRaises() in a test cases that raises multiple exceptions
Asked Answered
B

1

10

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.

Barbaric answered 17/9, 2018 at 20:16 Comment(5)
It suggests to me that there is too much code within the test method, and this should be split to 2 different tests.Wei
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.Gramophone
A catch block can catch multiple exceptions but logically only exception would be raised and during testing that would be tested.Intellectual
@Wei 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.Barbaric
This answer with a context manager is useful.Planet
L
15

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")
Loya answered 17/9, 2018 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.