0
我測試使用assertRaises一個例外,即使引發異常,它不是由assertRaisesassertRaises:雖然做了方法
這裏檢測的單元測試KeyError異常異常沒有提出是方法測試:
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)
而且測試代碼:
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()
但它不是按預期工作,得到如下錯誤:
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
什麼是錯的單元測試用例?
並不意味着,如果你是在攔網除外,這意味着將引發異常? –
沒有,'except'塊是例外時「中招」,意思是注意到了,但不上調。您可以選擇提高或處理它。 assertRaises()特別檢查引發行爲。 – JacobIRR
哦確定,究竟什麼是單元測試這種情況下,我們要優雅地處理異常並沒有引起任何的最佳方式,可只要登錄並繼續前進? –