ID EN
Unittest

assertRaises

Python 3.11

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.

Syntax

PYTHON
assertRaises(exception, callable, *args, **kwds)

Examples

Example 1
PYTHON
with self.assertRaises(SomeException):
    do_something()
Example 2
PYTHON
with self.assertRaises(SomeException) as cm:
    do_something()

the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)

See Also

assertRaises() assertRaises() assertRaises()