如果未引发异常,则通过 Python 单元测试 [英] Pass a Python unittest if an exception isn't raised
问题描述
在 Python unittest
框架中,是否有办法在未引发异常的情况下通过单元测试,否则通过 AssertRaise 失败?
In the Python unittest
framework, is there a way to pass a unit test if an exception wasn't raised, and fail with an AssertRaise otherwise?
推荐答案
如果我正确理解你的问题,你可以做这样的事情:
If I understand your question correctly, you could do something like this:
def test_does_not_raise_on_valid_input(self):
raised = False
try:
do_something(42)
except:
raised = True
self.assertFalse(raised, 'Exception raised')
...假设您有相应的测试,可以在无效输入上引发正确的Exception
,当然:
...assuming that you have a corresponding test that the correct Exception
gets raised on invalid input, of course:
def test_does_raise_on_invalid_input(self):
self.assertRaises(OutOfCheese, do_something, 43)
然而,正如评论中所指出的,您需要考虑您实际测试的是什么.很可能像这样的测试...
However, as pointed out in the comments, you need to consider what it is that you are actually testing. It's likely that a test like...
def test_what_is_42(self):
self.assertEquals(do_something(42), 'Meaning of life')
...更好,因为它测试系统所需的行为,如果出现异常就会失败.
...is better because it tests the desired behaviour of the system and will fail if an exception is raised.
这篇关于如果未引发异常,则通过 Python 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!