【问题标题】:How to test assertRaised with arguments correctly?如何正确测试带有参数的assertRaised?
【发布时间】:2021-03-19 19:03:08
【问题描述】:

我正在尝试测试(使用 unittest.TestCase)在将无效值传递给 deposit 方法时会引发 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 异常吗?

【问题讨论】:

  • 该方法返回值 None,而不是错误(因为您已捕获它),在打印后重新引发错误 (raise ValueError)。那至少应该删除TypeError
  • 你是对的,如果我在 print("ValueError was caught") 之后重新引发 Value 错误,当我在调试器中单步执行时会引发正确的 ValueError。那样的话,我不应该用aMethod方法测试,用deposit方法测试吧?这意味着即使引发了正确的异常,我仍然必须弄清楚测试失败的原因。

标签: python-3.x unit-testing exception typeerror python-unittest


【解决方案1】:

在查看了 Daryl Spitzer 的 this answer 之后,我能够让它工作。 因为deposit 方法有参数传递给它,所以我需要在断言中而不是在方法中指定它们。

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

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

错误的方式:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多