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

3

6

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?

Himself answered 7/1, 2013 at 15:44 Comment(0)
T
9

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.

Turbojet answered 7/1, 2013 at 15:52 Comment(0)
P
5

I think that self is being provided, but that assertRaises is expecting you to list the arguments separately. Try:

self.assertRaises(TypeError, self.calculator.add, 'hello', 4)
Pirtle answered 7/1, 2013 at 15:45 Comment(0)
S
1

You must pass the values this way:

self.assertRaises(TypeError, self.calculator.add, arg1, arg2, arg3)
Stryker answered 7/1, 2013 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.