如果未引发异常,则通过 Python 单元测试

编程入门 行业动态 更新时间:2024-10-24 12:22:40
本文介绍了如果未引发异常,则通过 Python 单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 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 单元测试

本文发布于:2023-10-31 05:02:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545080.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   异常   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!