且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用单元测试在 Python 的单个测试套件中运行多个类?

更新时间:2023-11-16 23:05:16

如果您想运行来自特定测试类列表的所有测试,而不是来自模块中所有测试类的所有测试,您可以使用 TestLoaderloadTestsFromTestCase 方法为每个类获取一个 TestSuite 测试,然后创建一个单独的组合 TestSuite 从包含您可以与 run 一起使用的所有套件的列表中:

If you want to run all of the tests from a specific list of test classes, rather than all of the tests from all of the test classes in a module, you can use a TestLoader's loadTestsFromTestCase method to get a TestSuite of tests for each class, and then create a single combined TestSuite from a list containing all of those suites that you can use with run:

import unittest

# Some tests

class TestClassA(unittest.TestCase):
    def testOne(self):
        # test code
        pass

class TestClassB(unittest.TestCase):
    def testOne(self):
        # test code
        pass

class TestClassC(unittest.TestCase):
    def testOne(self):
        # test code
        pass

def run_some_tests():
    # Run only the tests in the specified classes

    test_classes_to_run = [TestClassA, TestClassC]

    loader = unittest.TestLoader()

    suites_list = []
    for test_class in test_classes_to_run:
        suite = loader.loadTestsFromTestCase(test_class)
        suites_list.append(suite)
        
    big_suite = unittest.TestSuite(suites_list)

    runner = unittest.TextTestRunner()
    results = runner.run(big_suite)

    # ...

if __name__ == '__main__':
    run_some_tests()