-1
我正在學習python unitesting並想測試異常處理。爲什麼assertRaises沒有被抓住,我的單元測試失敗了?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,但它不會在任何地方引發。 –