2017-02-17 90 views
-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) 
+0

您正在引發RunTimeError,但在稍後捕獲它。 –

+0

我的第二個例子有什麼問題 –

+0

您試圖捕獲ValueError,但它不會在任何地方引發。 –

回答

0

因爲它沒有提出來;函數內部捕獲並處理異常。

在第二個示例中,您調用該函數並將結果傳遞給assertRaises,因此異常發生在assertRaises可以捕獲之前。您應該像在第一個示例中那樣使用上下文管理器方法,或者傳遞可調用方法:self.assertRaises(ValueError, abc, 2, msg=...)

+0

第二個例子有什麼問題。 –