2017-04-20 48 views
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 

什么是错的单元测试用例?

回答

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'块是例外时“中招”,意思是注意到了,但不上调。您可以选择提高或处理它。 assertRaises()特别检查引发行为。 – JacobIRR

+0

哦确定,究竟什么是单​​元测试这种情况下,我们要优雅地处理异常并没有引起任何的最佳方式,可只要登录并继续前进? –