2017-02-17 23 views
-1

私はPythonの実装を学び、例外処理をテストしたいと思っていました。なぜassertRaisesが捕まえられず、私のunittestが失敗するのですか?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

私の2番目の例の問題点 –

+0

ValueErrorをキャッチしようとしていますが、どこにも持ち上げられていません。 –

答えて

0

、それはそれは発生しませんので。例外はキャッチされ、関数内部で処理されます。

2番目の例では、関数を呼び出して結果をassertRaisesに渡すため、assertRaisesがキャッチする前に例外が発生します。最初の例のようにコンテキストマネージャの方法を使用するか、呼び出し可能な:self.assertRaises(ValueError, abc, 2, msg=...)を渡す必要があります。

+0

2番目の例の問題は何ですか? –

関連する問題