如何测试Python函数是否引发异常?

2022-09-05 01:07:38

如何编写仅当函数未引发预期异常时才失败的单元测试?


答案 1

使用 Unittest 模块中的 TestCase.assertRaises(或 ),例如:TestCase.failUnlessRaises

import mymod

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc)

答案 2

从Python 2.7开始,您可以使用上下文管理器来获取实际抛出的异常对象:

import unittest

def broken_function():
    raise Exception('This is broken')

class MyTestCase(unittest.TestCase):
    def test(self):
        with self.assertRaises(Exception) as context:
            broken_function()

        self.assertTrue('This is broken' in context.exception)

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

http://docs.python.org/dev/library/unittest.html#unittest.TestCase.assertRaises


Python 3.5中,你必须包装,否则你会得到一个context.exceptionstrTypeError

self.assertTrue('This is broken' in str(context.exception))

推荐