Three forms of unittest framework execution use cases

1. The way to execute test cases through testsuit: What if you only want to use a certain use case? How to do? Use the suite and pass in the method name of the test case

import unittest 

# 执行测试的类
class UCTestCase(unittest.TestCase):
    def setUp(self):
        #测试前需执行的操作
      
    def tearDown(self):
        #测试用例执行完后所需执行的操作
     
    # 测试用例1
    def test1(self):
        #具体的测试脚本
      
    # 测试用例2
    def test2(self):
        #具体的测试脚本
       
if __name__ == "__main__":
    # 构造测试集
    suite = unittest.TestSuite()
    suite.addTest(UCTestCase("test1"))
    suite.addTest(UCTestCase("test2"))
    # 执行测试
    runner = unittest.TextTestRunner()
    runner.run(suite)

2. Through the testLoader method: If there are multiple classes, I want to run the test cases under a certain class? Pass testLoader

import unittest

class TestCase1(unittest.TestCase):
    def testCase1(self):
    print("a")
    def testCase2(self):
    print("b")
 

class TestCase2(unittest.TestCase):
    def testCase1(self):
        print("a1")
    def testCase2(self):
        print("b1")
 
if __name__ == "__main__":
    #此用法可以同时测试多个类
    suite1 = unittest.TestLoader().loadTestsFromTestCase(TestCase1)
    suite2 = unittest.TestLoader().loadTestsFromTestCase(TestCase2)
    suite = unittest.TestSuite([suite1, suite2])

3. Load all test cases under a path through discover

import unittest

# discover可以一次调用多个脚本
# test_dir 被测试脚本的路径
# pattern 脚本名称匹配规则

test_dir = "./test_case"
discover = unittest.defaultTestLoader.discover(test_dir, pattern="test*.py")

# 匹配test_case目录下所有以test开头的py文件,执行这些py文件下的所有测试用例
if __name__ == "__main__":
    runner=unittest.TextTestRunner()
    runner.run(discover)

Guess you like

Origin blog.csdn.net/Python_BT/article/details/107888843