assertRaises:在对方法进行单元测试时不会引发KeyError异常

时间:2017-04-20 21:13:06

标签: python unit-testing assertraises

我正在使用assertRaises测试异常,即使引发了异常,assertRaises也没有检测到它

以下是测试中的方法:

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

单元测试用例有什么问题?

1 个答案:

答案 0 :(得分: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关键字引发错误不同。