Python中的自定义错误消息

时间:2014-10-14 18:45:11

标签: python unit-testing exception-handling error-handling

所以我正在练习一些单元测试,我对错误消息有疑问。我正在尝试创建一个自定义错误消息,该消息将在测试失败时显示。这是一个基本的Hello World程序。测试运行正常,但是这里是我收到的错误消息。

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)

超级基础,只想了解如何抛出自定义错误消息。如果测试失败,我唯一想看的是This is a custom error,我尝试按照关于错误和放大器的Python文档进行操作。这里有例外https://docs.python.org/2/tutorial/errors.html,但不确定如何实现它。

我不知道这是否可行。任何帮助是极大的赞赏。谢谢

1 个答案:

答案 0 :(得分:2)

你可以做的是通过将assertEqual包装在try except语句中来捕获AssertionError,然后打印错误:

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

捕获AssertionError时有一个缺点:unittest模块无法再计算错误。 (Stacktraces并不漂亮,但它们的目的是准确地指向发生错误的堆栈中的点。)

相关问题