Jamie Cele Jamie Cele - 3 months ago 24
Python Question

Python unittest testcase on catching error failing

So I have class Dog:

class Dog:

def __init__(self, res):
self._res = res

def error(self):
raise IndexError

and unit test:

class TestDog(unittest.TestCase):

def setUp(self):
self.dog = Dog([1,2])

def testError(self):
self.assertRaises(IndexError, self.dog.error())

Why is the testcase testError failing? self.dog.error() should result in IndexError being rasied, and I believe the assertRaises is correctly formatted.

Any help is appreciated, thanks.


When Python runs the line self.assertRaises(IndexError, self.dog.error()), it has to calculate the arguments of the method self.assertRaises before passing them to it, so it calls self.dog.error() which raises an error. This is how all functions work. The presence of self.assertRaises does nothing to stop the error being raised. You are meant to call self.assertRaises(IndexError, self.dog.error), where the second argument is now the actual function/method object self.dog.error without having called it yet. self.assertRaises will call it for you wrapped in a try/except so that it can do the test properly.


with self.assertRaises(IndexError):