-1

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?

  • Take a look at the signature for `assertRaises`: https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises – ddejohn Sep 15 '21 at 17:50
  • FYI, likely just pasted incorrectly , but your `except` is not properly indented. – ddejohn Sep 15 '21 at 17:57
  • Does this answer your question? [How do you test that a Python function throws an exception?](https://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception) – MrBean Bremen Sep 16 '21 at 05:41

1 Answers1

4

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.

chepner
  • 497,756
  • 71
  • 530
  • 681