你如何测试一个Python函数抛出异常?

如何编写一个单元测试,只有在函数没有抛出预期的异常时才会失败?


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

import mymod

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

自Python 2.7以来,您可以使用上下文管理器来获取抛出的实际Exception对象:

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中 ,你必须在str包装context.exception ,否则你会得到一个TypeError

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

我以前的答案中的代码可以简化为:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction)

如果函数需要参数,只需将它们传递给assertRaises,如下所示:

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction, arg1, arg2)
链接地址: http://www.djcxy.com/p/20857.html

上一篇: How do you test that a Python function throws an exception?

下一篇: How to make a custom exception class with multiple init args pickleable