How do you test that a Python function throws an exception?

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


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

import mymod

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

Since Python 2.7 you can use context manager to get a hold of the actual Exception object thrown:

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


In Python 3.5 , you have to wrap context.exception in str , otherwise you'll get a TypeError

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

The code in my previous answer can be simplified to:

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

And if afunction takes arguments, just pass them into assertRaises like this:

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

上一篇: Java可选参数

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