【发布时间】:2017-02-17 11:03:28
【问题描述】:
我正在学习 python 联合并想测试异常处理。为什么 assertRaises 没有被抓住而我的单元测试失败了?
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)
【问题讨论】:
-
你提出了 RunTimeError 但在几行之后才发现它。
-
我的第二个例子有什么问题
-
你试图捕捉 ValueError,但它没有在任何地方引发。
标签: python python-2.7 unit-testing