【问题标题】:Why doesn't Pythons unittest.assertRaises() raise an error here?为什么 Python 的 unittest.assertRaises() 不会在这里引发错误?
【发布时间】:2016-05-30 10:20:02
【问题描述】:

使用 Python 3.5,为什么下面的所有测试在运行时都通过了?既然调用div 时不会引发Exception,那么assertRaises() 怎么不抱怨?

根据assertRaises() 的文档:“如果没有引发异常,则失败”。

谁能帮帮我?

..
----------------------------------------------------------------------
Ran 2 tests in 0.002s




def div(self, x, y):
    if y == 0:
        raise Exception("Division by zero")
    return x / y

class MyTest(unittest.TestCase):

    def test1(self):
        with self.assertRaises(Exception) as cm:
            self.div(2, 1)

    def test2(self):
        self.assertRaises(Exception, div, 2, 1)

【问题讨论】:

  • 不要扔又抓Exception,因为很容易不小心抓到错误的东西,比如被扔在这里的TypeError

标签: python unit-testing


【解决方案1】:

因为您使用错误的签名调用了div,并且在调用div 之前引发了异常(div 的实际主体未执行,在执行之前引发了异常)。

更清楚了解正在发生的事情,请尝试在测试用例中将 ZeroDivisionErrordiv 提升并将 assertRaises(Exception, ... 替换为 assertRaises(ZeroDivisionError, ...

【讨论】:

  • 谢谢,但是在外面调用div时为什么会报错:“Exception was unhandled by user code”?
  • 听起来该消息来自一个奇怪的外壳,您正在其中运行。无论哪种方式,您都会收到该消息,因为 存在您的代码未处理的异常,就像消息中所说的那样
  • 确实,是 Visual Studio 造成了这些问题。从命令行 Python 运行良好.. 谢谢!
【解决方案2】:

调用self.div() 时会引发异常,因为您在MyTest 类之外定义了div 方法。

这就是为什么最好在测试中同时验证异常消息:

with self.assertRaises(Exception) as exc:
    self.div(2, 1)
self.assertEqual("Division by zero", str(exc.exception))

【讨论】:

  • 当 div 方法被正确调用时,我得到错误:“异常未被用户代码处理”(除以零)?这是为什么呢?
【解决方案3】:

你也可以使用:

self.assertRaises(Exception, lambda: div(2, 0))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2013-03-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多