如何使用单元测试在 Python 中的单个测试套件中运行多个类?
最佳答案
如果您想运行特定测试类列表中的所有测试,而不是模块中所有测试类中的所有测试,您可以使用 TestLoader
的loadTestsFromTestCase
方法为每个类获取一个 TestSuite
测试,然后从包含您所有这些套件的列表中创建一个组合的 TestSuite
可以与 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()
关于python - 如何使用单元测试在 Python 的单个测试套件中运行多个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5360833/