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

标签 python unit-testing

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

最佳答案

如果您想运行特定测试类列表中的所有测试,而不是模块中所有测试类中的所有测试,您可以使用 TestLoaderloadTestsFromTestCase 方法为每个类获取一个 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/

相关文章:

Python-Jupyter-h5py 的 'cannot import name _errors'

python - 如何使用 `venv`(在 Python 3.3+ 中)更新 Python 虚拟环境以使用较新版本的 Python?

java - Spring/Thymeleaf 单元测试 : test does not send value for model correctly

java - 如何使用私有(private)构造函数测试最终类?

c# - 如何为自定义数据注释进行单元测试

python - 使用 MinGW 在 Windows 上构建 lxml

python - Boost.Python 和错误 LNK1104 : cannot open file 'boost_python-vc100-mt-gd-1_55.lib'

java - JMockit:测试覆盖抽象方法的方法

python - 十六进制字符串转两个18位整数

python - 模拟 map_async 函数参数产生 PicklingError