我读过了this https://stackoverflow.com/questions/129507/how-do-you-test-that-a-python-function-throws-an-exception问答,并且已经尝试捕获我的代码中引发 IntegrityError 异常的异常,如下所示:
self.assertRaises(IntegrityError, db.session.commit())
但不知何故,我的单元测试仍然失败,并因 IntegrityError 异常而停止。我希望它会说“OK”,因为我已经预计在我的单元测试中会有例外。
这是由尝试插入具有相同唯一字段值的行的代码引起的。
任何想法?
其中之一就是诀窍:
# ... only if version >= 2.7
with self.assertRaises(IntegrityError):
db.session.commit()
Or:
self.assertRaises(IntegrityError, db.session.commit)
您的示例与正确方法之间的区别是:
# Your example: You call db.session.commit(), this will raise an exception before
# assertRaises is called
self.assertRaises(IntegrityError, db.session.commit())
# Correct way: Pass what should be called to assertRaises,
# let assertRaises invoke it and check for exception
self.assertRaises(IntegrityError, db.session.commit)
我更喜欢使用断言加注 http://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises作为上下文管理器(使用with
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)