Verify Expected Exceptions Precisely
Core idea
Use TestCase.assertRaises as a context manager around the operation expected to fail. It fails if no exception occurs; unexpected exception types propagate and are recorded as errors. assertRaisesRegex also checks the message with a regular expression. Keep setup outside the context so unrelated failures cannot satisfy the test.
import unittestdef quantity(n): if n < 0: raise ValueError('negative quantity') return nclass T(unittest.TestCase): def test_invalid(self): with self.assertRaises(ValueError) as caught: quantity(-2) self.assertEqual(str(caught.exception), 'negative quantity')print(T('test_invalid').run().wasSuccessful())The context stores the caught exception for later inspection.
Catch a missing validation
import unittestclass T(unittest.TestCase): def test_bad_input(self): with self.assertRaisesRegex(ValueError, 'negative'): abs(-2)r = T('test_bad_input').run()print(len(r.failures), len(r.errors))abs returns a value instead of raising, so the intentional test fails.
Common mistake
A broad Exception expectation may accept an unrelated error. Test the narrowest meaningful type and stable message fragments only if they are part of the contract.
Practice
Write one test for a negative quantity and one for zero. Change the implementation to raise TypeError instead of ValueError and inspect the error report.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exception tests
Check your understanding of exception tests.
What is printed?
import unittestclass T(unittest.TestCase): def test_a(self): with self.assertRaises(ValueError): int('bad')print(T('test_a').run().wasSuccessful())What is printed?
import unittestclass T(unittest.TestCase): def test_a(self): with self.assertRaises(ValueError): raise TypeError('bad')print(len(T('test_a').run().errors))Where should unrelated setup run?
What does assertRaisesRegex additionally verify?