在 python 中使用 xmlrunner 和 unittest 断言失败后继续测试

continue test after assertion fail using xmlrunner and unittest in python

我正在使用 XML运行ner 和 python 中的单元测试编写一个简单的测试。使用断言时,测试失败并且不会继续。我希望测试持续到最后然后失败。可能吗?我将附上一个非常简单的代码来演示我需要做什么。

import xmlrunner
import unittest

class TestExp(unittest.TestCase):

    def setUp(self):
        self.list = range(1,10)

    def test_example(self):
        for i in self.list:
            self.assertTrue(i == 3, str(i) + "message")


if __name__ == '__main__':
    unittest.main(
        testRunner=xmlrunner.XMLTestRunner(output='test-reports'),
        failfast=False, buffer=False, catchbreak=False)

作为输出,生成了一个 XML,但是只包含第一个失败的断言,我需要 运行 其余的断言,并从中生成测试报告,当使用 try/except 我在 XML 文件中看不到测试用例失败。

<?xml version="1.0" ?>
<testsuite errors="1" failures="0" name="TestExp-20150429152621" tests="1" time="0.000">
    <testcase classname="TestExp" name="test_example" time="0.000">
        <error message="1message" type="AssertionError">
<![CDATA[Traceback (most recent call last):
  File "xmlrunsample.py", line 14, in test_example
    self.assertTrue(i == 3, str(i) + "message")
AssertionError: 1message
]]>     </error>
    </testcase>
    <system-out>
<![CDATA[]]>    </system-out>
    <system-err>
<![CDATA[]]>    </system-err>
</testsuite>

这是我得到的测试报告输出,只包含 1 个断言失败,我怎样才能让脚本继续断言其余的测试用例?

您以错误的方式构建测试。测试运行器将此视为单个测试。当它捕捉到断言时,测试失败。

如果您想紧贴您的代码,您必须自己捕捉断言,并在最后重新抛出一个。这显然是臭代码,因为它使失败的来源不透明。

理想情况下,您必须重新设计您的测试。 如果你有相互独立的断言(即你对下一个感兴趣,即使前一个失败),你有独立的测试用例。 Testrunner 负责通过您的测试进行迭代,它会捕获每个断言并将其输出。

查看 the fine documentation 如何操作。

如果您正在寻找参数化测试用例,here on SO 是一个不错的主意,您可以从中着手。