我在我的单元测试中使用 assertRaises 来测试特定异常的引发。
assertRaises(IOError, testToRun, passedValues)
虽然我需要捕获的一些异常具有特定的错误编号 (errno),因此我不想收集基本异常,而是想捕获与该异常相关的特定错误编号。像这样的东西,虽然它显然不起作用:)
assertRaises(IOError.errno(2), testToRun, passedValue)
为了在我想捕获特定编号的异常时解决这个问题,我一直在使用:-
try:
testToRun(passedValues)
except IOError, e:
if e.errno == 2:
pass
else:
raise
我敢肯定它并不完美,但它确实有效,但我想知道是否可以使用 assertRaises 以更紧凑的方式来做同样的事情。
谢谢。
最佳答案
从 2.7 开始可以使用 assertRaises
使用上下文管理器:
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
关于python - 在单元测试中将 errno 与 assertRaises 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10167027/