如何编写仅在函数未引发预期异常的情况下失败的单元测试?
3 回答

慕莱坞森
TA贡献1810条经验 获得超4个赞
使用unittest模块中的TestCase.assertRaises(或TestCase.failUnlessRaises),例如:
import mymod
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc)

慕盖茨4494581
TA贡献1850条经验 获得超11个赞
我上一个答案中的代码可以简化为:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction)
如果函数接受参数,则将它们传递给assertRaises,如下所示:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction, arg1, arg2)
添加回答
举报
0/150
提交
取消