This advertisement helps me to keep writing articles on this website

Check for an exception (raise Error) in a Python unit test.

assertRaises can be used to check if your functions raise certain errors. But what if the assertRaises test still throws an error? Perhaps you are calling the function instead of passing it to the assertRaises method. This example shows how to call functions -with arguments- that can raise errors

Here is a function that says hello. If the name is an empty string, it raises an error.

def say_hello(name):
    if name == "":
        raise ValueError("Name is empty")
    return "Hello " + name

To test for succes, you use the assertEqual method. But how can you test if the functions raises the proper error when you pass an empty string?

assertRaises for functions with parameters

import unittest

class HelloTests(unittest.TestCase):
    def test_hello(self):
        self.assertEqual(say_hello("Loek"), "Hello Loek")

    def test_no_name(self):
        self.assertRaises(ValueError, say_hello, "")

In the last line, you see how the assertRaises method is called. You cannot use the syntax: self.assertRaises(ValueError, say_hello("")). This would execute the function and raise an actual error. Note that this is also true for functions without arguments. In any case, with or without arguments, you should pass the function, not call the function!

When using the assertRaises method, the parentheses () need to be omitted and the arguments are passed after the function name, comma separated.

self.assertRaises(ValueError, say_hello, "")

Output:

python3 -m unittest -v
test_hello (tests.test_hello.HelloTests) ... ok
test_no_name (tests.test_hello.HelloTests) ... ok
Written by Loek van den Ouweland on August 22, 2020. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.