我正在尝试测试(使用unittest.TestCase),当一个无效值被传递给存放方法时,是否会引发ValueError异常,但当它被引发时,测试就会失败。我已经在调试器中单步执行了测试,它确实到达了raise ValueError行,但由于某些原因,测试仍然失败。我甚至尝试过引发和断言其他异常,但测试仍然失败。
我的方法是:
def deposit(self, amount):
if (not isinstance(amount, float)) and (not isinstance(amount, int)):
raise ValueError我的测试:
def test_illegal_deposit_raises_exception(self):
self.assertRaises(ValueError, self.account.deposit("Money"))然后我想它可能失败了,因为异常还没有被捕捉到。因此,我在对象的类中添加了一个方法来调用deposit方法来捕获ValueError异常。
def aMethod(self):
try:
self.deposit("Money")
except ValueError:
print("ValueError was caught")然而,现在测试失败了,因为我得到了一个TypeError异常。Here is an other debug image
TypeError: 'NoneType' object is not callable谁能解释一下为什么我会得到一个TypeError异常,而不是我引发的ValueError异常?
发布于 2020-12-09 11:53:22
在看了Daryl Spitzer的this answer之后,我能够让它工作起来。因为deposit方法有传递给它的参数,所以我需要在断言中而不是在方法中指定它们。
测试异常的正确方法是:
self.assertRaises(ValueError, self.account.deposit, "Money")错误的方式:
self.assertRaises(ValueError, self.account.deposit("Money"))https://stackoverflow.com/questions/65199251
复制相似问题