如何测试Python函数是否抛出异常?
怎么写一个单元测试,让它只在某个函数没有抛出预期的异常时才失败呢?
19 个回答
529
我之前回答的代码可以简化成这样:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction)
如果一个函数需要参数,只需像这样把它们传递给assertRaises:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction, arg1, arg2)
695
从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()
在Python 3.5中,你需要把context.exception
用str
包裹起来,否则会出现TypeError
错误。
self.assertTrue('This is broken' in str(context.exception))
1003
使用来自 unittest
模块的 TestCase.assertRaises
方法,举个例子:
import mymod
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc)