Categories
Python Answers

How to test that a Python function throws an exception?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *