How do I run multiple Classes in a single test suite in Python using unit testing?

后端 未结 5 1052
无人共我
无人共我 2021-02-01 03:09

How do I run multiple Classes in a single test suite in Python using unit testing?

5条回答
  •  轮回少年
    2021-02-01 03:28

    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()
    

提交回复
热议问题