How can I test that a function raises the expected exception?
Quick answer
In Python’s unittest framework, put the invalid function call inside with self.assertRaises(ExpectedError):. The test checks for that expected exception type rather than treating any failure as success. Keep the context focused on the call you expect to fail; setup or other code inside it could otherwise raise the exception and make the test misleading. [S1]
The question, the details, the next step.
A practical checklist
Choose the specific invalid input the test is meant to cover.
Use the exception type the function is expected to raise.
Put only the invalid function call inside
with self.assertRaises(...).Keep setup and unrelated assertions outside the context.
Use a test name that describes the invalid case and expected exception.
A few more useful answers
Does this test check the exception message too?
The example checks that the call raises the specified exception type. It does not check the exception message; add a separate assertion if that detail matters.
What if the function is not supposed to raise an exception?
Call it normally in a test and check its expected result. Do not put that call inside assertRaises, which is for calls expected to raise an exception. [S1]
Does one passing exception test prove all invalid inputs are handled?
No. It shows that the tested call raised the specified exception type. Add separate focused cases for other invalid inputs or behaviors you need to check.
Sources
References used for this guide.
- [S1] Python unittest: TestCase assertions and exception checks docs.python.org · Checked
