Python - 未引发异常时测试成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/647900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - test that succeeds when exception is not raised
提问by Anonymous
I know about unittest
Python module.
我知道unittest
Python 模块。
I know about assertRaises()
method of TestCase
class.
我知道类的assertRaises()
方法TestCase
。
I would like to write a test that succeeds when an exception is notraised.
我想编写一个在未引发异常时成功的测试。
Any hints please?
请问有什么提示吗?
采纳答案by Anonymous
The test runner will catch all exceptions you didn't assert would be raised. Thus:
测试运行程序将捕获您未断言将引发的所有异常。因此:
doStuff()
self.assert_(True)
This should work fine. You can leave out the self.assert_ call, since it doesn't really do anything. I like to put it there to document that I didn't forget an assertion.
这应该可以正常工作。您可以省略 self.assert_ 调用,因为它实际上并没有做任何事情。我喜欢把它放在那里来证明我没有忘记一个断言。
回答by Hank Gay
def runTest(self):
try:
doStuff()
except:
self.fail("Encountered an unexpected exception.")
UPDATE: As liw.fi mentions, the default result is a success, so the example above is something of an antipattern. You should probably only use it if you want to do something special before failing. You should also catch the most specific exceptions possible.
更新:正如 liw.fi 提到的,默认结果是成功,所以上面的例子是一种反模式。如果您想在失败之前做一些特别的事情,您可能应该只使用它。您还应该尽可能捕获最具体的异常。
回答by kosii
I use this pattern for the kind of assertion you've asked:
我将这种模式用于您提出的那种断言:
with self.assertRaises(Exception):
try:
doStuff()
except:
pass
else:
raise Exception
It will fail exactly when exception is raised by doStuff().
当 doStuff() 引发异常时,它将完全失败。