断言在unittest中引发,未正确捕获异常 [英] assertRaises in unittest not catching Exception properly
本文介绍了断言在unittest中引发,未正确捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含代码的文件testest.py
import unittest
def add(self, a, b):
return a + b
class Test(unittest.TestCase):
def test_additon(self):
self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
#self.assertRaises(TypeError, lambda: add(1 + '1'), msg="Addition failed")
if __name__ == '__main__':
unittest.main()
问题是assertRaises
没有正确捕获异常,并且我的所有测试都作为错误持续失败,这是我得到的输出:
E
======================================================================
ERROR: test_additon (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "testtest.py", line 9, in test_additon
self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
我知道我可以通过使用lambda(我在代码中将其注释掉)来绕过它,以使我的测试正确地捕获异常,但根据文档,将一个可调用函数和参数传递给assertRaises
应该是可行的,因为它将在内部自行调用该函数,并能够捕获引发的任何异常。
assertRaises(*callable*, *args*, *kwargs*)
但它不是
如果我用lambda运行它,这是一个稍后将由assertRaises
计算的可调用函数,它会按预期工作,我会得到这样的结果
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
I'm running python 3.5
Python 3.5.2 (default, Jun 28 2016, 08:46:01)
[GCC 6.1.1 20160602] on linux
但我也使用python2.7
推荐答案
您应该将参数作为单独的参数分别传递给可调用的:
self.assertRaises(TypeError, add, 1, '1', msg="Additon failed")
这篇关于断言在unittest中引发,未正确捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文