Code # 1: Check that the function raised a ValueError
|
Code # 2 : need to check the value of the exception with a different approach
|
The assertRaises ()
method provides a convenient way to check for an exception. A common mistake is writing tests that manually try to do something with exceptions on their own.
Code # 3: Example
|
The problem with such approaches is that it’s easy to forget about corner cases, such as the case where no exceptions are thrown. To do this, you need to add an extra check for this situation as shown in the code below.
Code # 4:
|
The assertRaises ()
method just takes care of these details, so it’s preferred to use it. The only limitation of assertRaises ()
is that it does not provide a means to validate the value of the generated exception object.
To do this, it must be manually checked. Somewhere in between these two extremes, you can use the assertRaisesRegex () method which allows you to check for an exception while matching the regular expression against the string representation of the exception.
Code # 5:
|
Little known fact about assertRaises ()
and assertRaisesRegex ()
is that they can also be used as context managers.
Code # 6:
|
This form can be useful if a test has multiple steps (such as customization) besides just executing the called one.