接上篇,先了解一下这个类 TestSuite(BaseTestSuite)。
class TestSuite(BaseTestSuite):
"""A test suite is a composite test consisting of a number of TestCases.
For use, create an instance of TestSuite, then add test case instances.
When all tests have been added, the suite can be passed to a test
runner, such as TextTestRunner. It will run the individual test cases
in the order in which they were added, aggregating the results. When
subclassing, do not forget to call the base class constructor.
"""
这个解释很明确了,测试集就是一系列case的组合。使用的时候,需要创建实例,然后添加需要运行的case,其他的case就不会被运行了。满足我们某个测试集只需要执行指定案例的需求。
文件名:calculator.py
类名:Jessi
class Jessi:
def __init__(self, a, b):
self.a = a
self.b = b
def count(self):
return self.a + self.b
def minus(self):
return self.a - self.b
文件名:003_unittest_测试集.py
import unittest
from again.base_agin.fun.calculator import Jessi
class TestCal(unittest.TestCase):
def setUp(self) -> None:
print('start')
def test01(self):
j = Jessi(1, 2)
try:
self.assertEqual(j.count(), 5)
except AssertionError as msg:
print(msg)
def test02(self):
j = Jessi(6, 2)
self.assertEqual(j.minus(), 4)
def tearDown(self) -> None:
print('end')
# if __name__ == '__main__':
# unittest.main()
suit = unittest.TestSuite() # 申请测试集套件对象
suit.addTest(TestCal('test01')) # 添加测试案例 类名(函数名)
# suit.addTest(TestCal('test02'))
runner = unittest.TextTestRunner() # 申请执行测试的对象
runner.run(suit)
如上,添加‘’test02‘’被注释掉了,所以不会执行。
如果遇到,仅添加部分案例,但实际却全部case都运行了,解决办法可参考这里