Sometimes, we want to test that a Python function throws an exception.
In this article, we’ll look at how to test that a Python function throws an exception.
How to test that a Python function throws an exception?
To test that a Python function throws an exception, we can use the assertRaises
method.
For instance, we write
import my_mod
#...
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeException, my_mod.my_func)
to create the MyTestCase
test class.
In it, we define the test1
test method that calls assetRaises
with the exception we want to check for and the function that throws the exception respectively.
Conclusion
To test that a Python function throws an exception, we can use the assertRaises
method.