Search code examples
pythonunit-testingtry-catchpython-unittest

How to assert for exceptions with python library unittest


I have a dummy funtion to try exceptions:

def fun(n):
    try:
        if n <1:
            raise ValueError
        return 1
        except:
            pass

In my unit test I use:

import  unittest
class TestFibonnacci(unittest.TestCase):
    def test_values(self):
        self.assertEqual(fun(1),1)
        self.assertRaises(ValueError, fun(-1))

However I'm unable to get an answer I actually get:

An exception occurred E.... ERROR: test_values (main.TestFibonnacci)

Traceback (most recent call last): The traceback here

TypeError: 'NoneType' object is not callable

Ran 1 tests in 0.001s

What I'm doing wrong?


Solution

  • You are calling fun(-1) immediately, rather than letting self.assertRaises call it, so that it can catch the exception.

    You have to pass the function and its arguments separately.

    self.assertRaises(ValueError, fun, -1)
    

    Alternatively, you can use assertRaises as a context manager.

    with self.assertRaises(ValueError):
        fun(-1)
    

    The with statement captures the exception raised by fun and provides it to the __exit__ method of the value returned by assertRaises.