2017-04-20 1 views
0

이 예외가 발생하더라도, 그것이 assertRaises 여기 assertRaises : I가 assertRaises를 사용하여 예외를 테스트하고

의해 검출되지 않는 방법의 단위 테스트를하는 동안 KeyError를 예외가 발생되지 않고, 피 시험 방법 :

import unittest 
import test_exception 


class TestExceptions(unittest.TestCase): 
    """ 
    test class 
    """ 
    def test_process_data(self): 
     """ 
     test 
     :return: 
     """ 
     sample = {} 
     self.assertRaises(KeyError, test_exception.process_data, sample) 

if __name__ == '__main__': 
    unittest.main() 

그러나 예상지고 다음 오류로 작동하지 않는 경우 :

def process_data(data): 
    """ 
    process output data 
    :return: dict object 
    """ 
    component = dict() 
    try: 
     properties = dict() 
     properties['state'] = data['state'] 
     properties['status'] = data['status'] 
     component['properties'] = properties 
    except KeyError as e: 
     print "Missing key '{0}' in the response data".format(str(e)) 

    return component 

sample_data = {} 
process_data(sample_data) 

그리고 테스트 코드는

unittest -p test_test_exception.py 
Missing key ''state'' in the response data 


Missing key ''state'' in the response data 


Failure 
Traceback (most recent call last): 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 331, in run 
    testMethod() 
    File "/unittest/test_test_exception.py", line 16, in test_process_data 
    self.assertRaises(KeyError, test_exception.process_data, sample) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 475, in assertRaises 
    callableObj(*args, **kwargs) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 116, in __exit__ 
    "{0} not raised".format(exc_name)) 
AssertionError: KeyError not raised 



Ran 1 test in 0.001s 

FAILED (failures=1) 

Process finished with exit code 1 

단위 테스트 케이스에 어떤 문제가 있습니까?

답변

0

올바른 컨텍스트와 코드를 사용하여 명확한 질문을 게시 해 주셔서 감사합니다. 여기에 문제는 다음과 같습니다

except KeyError as e: 
    print "Missing key '{0}' in the response data".format(str(e)) 

이 있어야한다 :

except KeyError as e: 
    print "Missing key '{0}' in the response data".format(str(e)) 
    raise 

귀하의 단위 테스트 (코드가 완전히 단락입니다) 예외가 발생하는 것이 확인된다. 예외 유형을 찾고 메시지를 인쇄하는 것은 raise 키워드로 오류를 제기하는 것과 같지 않습니다.

+0

예외를 발생시키는 것을 의미하는 예외 블록에있는 것은 아닙니다. –

+0

아니요, 'except'블록은 예외가 "catch"된 것으로 의미가 있지만 발생하지 않은 경우를위한 것입니다. 그것을 제기하거나 처리 할 수있는 선택권이 있습니다. assertRaises()는 특히 그 상승 행동을 검사하고 있습니다. – JacobIRR

+0

오, 좋아, 그럼 우리가 정상적으로 예외를 처리하고 아무것도 인상하지 않으려는 단위 테스트에 가장 좋은 방법은 무엇일까요? –