Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用assertRaises在Python中测试实例方法?_Python_Unit Testing_Assertraises - Fatal编程技术网

如何使用assertRaises在Python中测试实例方法?

如何使用assertRaises在Python中测试实例方法?,python,unit-testing,assertraises,Python,Unit Testing,Assertraises,我知道如何在函数或lambda上使用assertRaises,但我想在实例方法上使用它 例如,如果我有一个类calculator,它执行无限精度的算术运算,我可能会编写测试: def setUp(self): self.calculator = calculator.calculator() def test_add(self): self.assertRaises(TypeError, self.calculator.add, ['hello', 4]) 因为self.ca

我知道如何在函数或lambda上使用
assertRaises
,但我想在实例方法上使用它

例如,如果我有一个类
calculator
,它执行无限精度的算术运算,我可能会编写测试:

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

def test_add(self):
    self.assertRaises(TypeError, self.calculator.add, ['hello', 4])
因为
self.calculator.add
是可调用的,并且
['hello',4]
是我希望传递的参数,但是,当我运行测试时,我得到以下致命错误:

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

我认为它抛出了这个错误,因为当
self.assertRaises
调用
self.calculator.add
时,
self
不会像调用实例方法时那样作为第一个片段传递。如何解决此问题?

您必须通过以下方式传递值:

self.assertRaises(TypeError, self.calculator.add, arg1, arg2, arg3)

我认为提供了
self
,但是
assertRaises
希望您单独列出参数。尝试:

self.assertRaises(TypeError, self.calculator.add, 'hello', 4)

正如其他答案所说,您必须单独传递值,但您可能会发现另一种更容易阅读的方法是使用
with
语句:

def test_add(self):
    with self.assertRaises(TypeError):
        self.calculator.add('hello', 4)
当您以这种方式使用
assertRaises
时,您只需在
with
块中正常编写代码。这意味着这是一种更自然的编码方式,而且您不局限于测试单个函数调用