Python - test that succeeds when exception is not raised

℡╲_俬逩灬. 提交于 2020-01-12 13:41:32

问题


I know about unittest Python module.

I know about assertRaises() method of TestCase class.

I would like to write a test that succeeds when an exception is not raised.

Any hints please?


回答1:


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.




回答2:


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.




回答3:


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().



来源:https://stackoverflow.com/questions/647900/python-test-that-succeeds-when-exception-is-not-raised

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!