如何在Python单元测试中运行Single Test Suite中的多个类?

pas*_*ime 26 python unit-testing

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

rak*_*ice 35

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

if __name__ == '__main__':
    # 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)

    # ...
Run Code Online (Sandbox Code Playgroud)


tdd*_*ing 14

我对你在这里要求的内容有点不确定,但是如果你想知道如何在同一个套件中测试多个类,通常你只需在同一个python文件中创建多个测试类并一起运行它们:

import unittest

class TestSomeClass(unittest.TestCase):
    def testStuff(self):
            # your testcode here
            pass

class TestSomeOtherClass(unittest.TestCase):
    def testOtherStuff(self):
            # testcode of second class here
            pass

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

并运行例如:

python mytestsuite.py
Run Code Online (Sandbox Code Playgroud)

更好的例子可以在官方文件中找到.

另一方面,如果你想运行多个测试文件,详见"如何以一种我可以在一个命令中运行所有测试的方式组织python测试?" ,那么另一个答案可能更好.


pds*_*pds 6

所述unittest.TestLoader.loadTestsFromModule()方法将发现和加载指定模块中的所有类。所以你可以这样做:

import unittest
import sys

class T1(unittest.TestCase):
  def test_A(self):
    pass
  def test_B(self):
    pass

class T2(unittest.TestCase):
  def test_A(self):
    pass
  def test_B(self):
    pass

if __name__ == "__main__":
  suite = unittest.TestLoader().loadTestsFromModule( sys.modules[__name__] )
  unittest.TextTestRunner(verbosity=3).run( suite )
Run Code Online (Sandbox Code Playgroud)