如何正确测试带参数的assertRaished?

问题描述 投票:0回答:1

我正在尝试测试(使用unittest.TestCase)当将无效值传递给存款方法时是否会引发

ValueError
异常,但在引发该异常时测试失败。我已经在调试器中逐步完成了测试,它确实达到了
raise ValueError
线,但由于某种原因测试仍然失败。 我什至尝试过引发和断言其他异常,但测试仍然失败。

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

python-3.x unit-testing exception typeerror python-unittest
1个回答
1
投票

看了达里尔·斯皮策 (Daryl Spitzer) 的这个答案后,我能够让它工作。

assertRaises()的 Python 文档 - 由于

assertRaises()
调用提供的
deposit()
方法,我需要在
assertRaises()
参数中提供调用参数 - 而不是在
deposit()
方法调用中。

引发测试异常的正确方法:

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

错误方式:

self.assertRaises(ValueError, self.account.deposit("Money"))
© www.soinside.com 2019 - 2024. All rights reserved.