我正在学习python unitesting并想测试异常处理。为什么assertRaises没有被抓住而我的unittest失败了?
def abc(xyz):
print xyz
try:
raise RuntimeError('I going to raise exception')
except ValueError, e:
print e
except RuntimeError, e:
print e
except Exception, e:
print e
import unittest
class SimplisticTest(unittest.TestCase):
def test_1(self):
with self.assertRaises(RuntimeError):
abc(2)
if __name__ == '__main__':
unittest.main()
2
F
I going to raise exception
======================================================================
FAIL: test_1 (__main__.SimplisticTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/d066537/ClionProjects/pythonspark/sample.py", line 18, in test_1
abc(2)
AssertionError: RuntimeError not raised
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
为什么测试失败以及如何纠正它。 问题是这个问题:
def abc(xyz):
print xyz
raise ValueError('I going to raise exception')
import unittest
class SimplisticTest(unittest.TestCase):
def test_1(self):
self.assertRaises(ValueError, abc(2), msg="Exception not getting caught")
if __name__ == '__main__':
unittest.main()
2
E
======================================================================
ERROR: test_1 (__main__.SimplisticTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/d066537/ClionProjects/pythonspark/sample.py", line 12, in test_1
self.assertRaises(ValueError, abc(2), msg="Exception not getting caught")
File "/home/d066537/ClionProjects/pythonspark/sample.py", line 3, in abc
raise ValueError('I going to raise exception')
ValueError: I going to raise exception
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
答案 0 :(得分:0)
因为它没有提高它;函数内部捕获并处理异常。
在第二个示例中,您调用函数并将结果传递给assertRaises,因此异常发生在assertRaises可以捕获它之前。您应该像在第一个示例中那样使用上下文管理器方法,或者传递callable:git diff <HASH>
。