前文:
Unittest 单元测试框架1 - 基本使用和命令行选项
Unittest 单元测试框架2 - 编写测试代码以及如何跳过测试用例
使用子测试区分测试迭代
3.4 新版本功能
当测试之间存在非常小的差异时,例如某些参数,unitest
允许您使用subTest()
上下文管理器在测试方法的主题中区分它们。
例如,以下测试:
class NumberTest(unittest.TestCase):
def test_even(self):
"""
Test that numbers between 0 and 5 are all even.
"""
for i in range(0, 6):
with self.subTest(i=i):
self.assertEqual(i % 2, 0)
可以得到以下输出:
======================================================================
FAIL: test_even (__main__.NumbersTest) (i=1)
Test that numbers between 0 and 5 are all even.
----------------------------------------------------------------------
Traceback (most recent call last):
File "E:/010temp/temp/temp_002.py", line 13, in test_even
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
======================================================================
FAIL: test_even (__main__.NumbersTest) (i=3)
Test that numbers between 0 and 5 are all even.
----------------------------------------------------------------------
Traceback (most recent call last):
File "E:/010temp/temp/temp_002.py", line 13, in test_even
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
======================================================================
FAIL: test_even (__main__.NumbersTest) (i=5)
Test that numbers between 0 and 5 are all even.
----------------------------------------------------------------------
Traceback (most recent call last):
File "E:/010temp/temp/temp_002.py", line 13, in test_even
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=3)
Process finished with exit code 1
原文来自于https://docs.python.org/3.9/library/unittest.html#
如有侵权,请联系删除