如何使用单元测试在 Python 的单个测试套件中运行多个类? [英] How do I run multiple Classes in a single test suite in Python using unit testing?

查看:44
本文介绍了如何使用单元测试在 Python 的单个测试套件中运行多个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

如果您想运行来自特定测试类列表的所有测试,而不是来自模块中所有测试类的所有测试,您可以使用 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()

这篇关于如何使用单元测试在 Python 的单个测试套件中运行多个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆