Python unittest如何在单个测试用例中输出所有AssertionError
解决方案
unittest 默认会在单个测试方法的第一个断言失败时终止执行,因此后续断言不会运行也不会输出错误。要在不新增测试用例的前提下输出同一测试用例内所有断言错误,可使用以下两种无额外依赖的方案:
方案1:使用unittest内置subTest上下文管理器(推荐)
这是unittest官方原生支持的功能,专门适配单测试方法下多测试点的场景,单个子测试失败不会中断其他子测试运行,所有失败结果会被汇总输出。
修改后代码如下:
import unittest def lbs_to_stones(lbs): return lbs/14 class Tests(unittest.TestCase): def test_lbs_to_stones(self): # 每个测试点放在独立的subTest上下文内 with self.subTest(lbs=140): self.assertEqual(lbs_to_stones(140),10) with self.subTest(lbs=150): self.assertEqual(lbs_to_stones(150),11) with self.subTest(lbs=14): self.assertEqual(lbs_to_stones(14),61) if __name__ == '__main__': unittest.main()
运行后会同时输出lbs=150和lbs=14两个测试点的断言错误,不会在第一个失败后终止执行。
方案2:手动收集错误统一抛出
如果不想使用subTest,也可以自行捕获每个断言的错误,全部测试点执行完成后汇总输出:
修改后代码如下:
import unittest def lbs_to_stones(lbs): return lbs/14 class Tests(unittest.TestCase): def test_lbs_to_stones(self): errors = [] # 捕获第一个测试点的错误 try: self.assertEqual(lbs_to_stones(140),10) except AssertionError as e: errors.append(f"lbs=140 断言失败: {str(e)}") # 捕获第二个测试点的错误 try: self.assertEqual(lbs_to_stones(150),11) except AssertionError as e: errors.append(f"lbs=150 断言失败: {str(e)}") # 捕获第三个测试点的错误 try: self.assertEqual(lbs_to_stones(14),61) except AssertionError as e: errors.append(f"lbs=14 断言失败: {str(e)}") # 汇总所有错误统一抛出 if errors: raise AssertionError("\n".join(errors)) if __name__ == '__main__': unittest.main()
运行后会将所有捕获到的断言错误一次性打印输出。
内容的提问来源于stack exchange,提问作者Tiago Mendes
相关产品推荐
相关产品推荐

