I want to know how to assert a raised exception in Python? I tried it with assertRaises(ExpectedException) but the test failed and the console output told me that the expected Exception was raised.
So how could I write this, so that the Exception is captured and asserted right?
Asked
Active
Viewed 1,928 times
-2
2 Answers
1
AssertRaises() can test all exception which you raise from the code.
The syntax for using assertRaises is:
assertRaises(CustomException, Function that throws the exception, Parameters for function(In case of multiple params, they will be comma separated.))
How it works:
When assertRaises is encountered, pyUnit executes the function mentioned inside a Try-Except block with the except block containing the CustomException. If the exception is properly handled, the test passes else it fails.
More on assertRaises can be found at How to properly use unit-testing's assertRaises() with NoneType objects?.
0
This will happen if the module throwing the exception and your test code refer to the exception in a different namespace.
So, for example, if you have:
# code_to_be_tested.py
from module_with_exception import * # including CustomException
...
raise CustomException()
# test_code.py
import module_with_exception.CustomException as CE
...
with assertRaises(CE) ...
This happens because the two files actually end up pointing to different classes/objects.
So, two ways around this:
- refer to them in the same way, if at all possible
- if you did something like
from blah import *
, grab the exception from the test module itself, as that's the one it's raising (ie,from code_to_be_tested import CustomException
)

sapi
- 9,944
- 8
- 41
- 71