gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:30:14 25 4
gpt4 key购买 nike

我了解如何在函数或 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] 是我想传递给它的参数,但是,当我运行测试时我收到以下 fatal error :

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

我认为它会引发此错误,因为当 self.assertRaises 调用 self.calculator.add 时,self 未被传递作为第一个参数,通常是在调用实例方法时。我该如何解决这个问题?

最佳答案

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

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

当您以这种方式使用 assertRaises 时,您只需在 with block 中正常编写代码。这意味着它是一种更自然的编码方式,而且您不仅限于测试单个函数调用。

关于python - 如何使用 assertRaises 在 Python 中测试实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14199197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com