python-3.x 如何正确测试带参数的assertRaised?

sigwle7e  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(115)

我尝试测试(使用unittest.TestCase)当一个无效的值被传递到存款方法时,会引发ValueError异常,但是当它被引发时测试失败。我已经在调试器中逐步完成了测试,它确实到达了raise ValueError行,但是由于某种原因测试仍然失败。我甚至尝试用其他异常引发和Assert,测试仍然失败。
Here is a debug image
我的方法:

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异常吗?

kr98yfug

kr98yfug1#

在看了Daryl Spitzer的this answer之后,我能够让它工作。
Python docs for assertRaises()-由于assertRaises()调用提供的deposit()方法,我需要在assertRaises()参数中提供调用参数-而不是在deposit()方法调用中。
测试Exception的 * 正确 * 方法是:

self.assertRaises(ValueError, self.account.deposit, "Money")

字符串

  • 错误的 * 方式:
self.assertRaises(ValueError, self.account.deposit("Money"))

相关问题