Python中的自定义错误消息

3 投票
1 回答
5550 浏览
提问于 2025-04-27 13:58

我在练习单元测试,遇到了一个关于错误信息的问题。我想创建一个自定义的错误信息,当测试失败时能够显示出来。这里有一个基本的“你好,世界”程序。测试运行得很好,但我得到的错误信息是这样的。

F ====================================================================== FAIL: test_StringContains
 (__main__.TestSuite) ----------------------------------------------------------------------   
Traceback    (most recent call last): File "Testsuite.py", line 8, in test_StringContains 
self.assertEqual("Hello,    World", hello_world,"This is a custom error") AssertionError: 'Hello,   
World' != 'Hello World' - Hello,    World ? - + Hello World : This is a custom error ---------------  
------------------------------------------------------- 
Ran 1 test in 0.000s FAILED (failures=1)

这其实是可以预期的。下面是我的测试套件。

from  HelloWorld import*
import unittest

class TestSuite(unittest.TestCase):

    def test_StringContains(self):
            self.assertEqual("Hello World", hello_world,"This is a custom")


if __name__ == "__main__":
    unittest.main()

这是我的运行代码。

hello_world = "Hello World"
print (hello_world)

非常简单,我只是想明白如何抛出一个自定义的错误信息。我希望在测试失败时看到的唯一信息是 这是一个自定义错误。我试着按照Python文档中关于错误和异常的部分来做,链接在这里 https://docs.python.org/2/tutorial/errors.html,但我不太确定该怎么实现。

我不知道这是否可行。任何帮助都非常感谢。谢谢!

暂无标签

1 个回答

4

你可以通过把assertEqual放在一个try except语句里来捕捉AssertionError,然后打印出错误信息:

        try:
            self.assertEqual("Hello World", hello_world,"This is a custom error")
        except AssertionError as e:
            print(e)

不过,捕捉AssertionError也有一个缺点:unittest模块就无法再统计错误的数量了。虽然错误追踪信息看起来不太美观,但它的作用是准确地告诉你错误发生的具体位置。

撰写回答