pythonunit-testingassertraises

How do you test an instance method in Python with assertRaises?


I understand how to use assertRaises on a function or a lambda, but I wanted to use it on an instance method.

So for example, if I have a class calculator that does infinite precision arithmetic, I might write the test:

def setUp(self):
    self.calculator = calculator.calculator()

def test_add(self):
    self.assertRaises(TypeError, self.calculator.add, ['hello', 4])

Because self.calculator.add is callable and ['hello', 4] are the arguments I would like to pass it, however, when I run the test I get the following fatal error:

TypeError: add() missing 1 required positional argument: 'num2'

I believe it is throwing this error because when self.assertRaises is calling self.calculator.add, self isn't being passed as the first arugment like it generally is when an instance method is called. How do I fix this?


Solution

  • As the other answers said you must pass the values separately, but an alternative which you may find reads more easily is to use the with statement:

    def test_add(self):
        with self.assertRaises(TypeError):
            self.calculator.add('hello', 4)
    

    When you use assertRaises this way you just write the code normally inside the with block. This means it's a more natural way to code, and also you aren't limited to just testing a single function call.