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?
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