使用 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 中 ,必须将context.exception
包装在str
,否则将收到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)