试图实现python TestSuite

avo*_*iva 28 python unit-testing regression-testing test-suite python-unittest

我有两个测试用例(两个不同的文件),我想在测试套件中一起运行.我可以通过"正常"运行python来运行测试但是当我选择运行python-unit测试时它会说0个测试运行.现在我只想尝试至少进行一次测试才能正确运行.

import usertest
import configtest # first test
import unittest   # second test

testSuite = unittest.TestSuite()
testResult = unittest.TestResult()
confTest = configtest.ConfigTestCase()
testSuite.addTest(configtest.suite())
test = testSuite.run(testResult)
print testResult.testsRun # prints 1 if run "normally"
Run Code Online (Sandbox Code Playgroud)

这是我的测试用例设置的一个例子

class ConfigTestCase(unittest.TestCase):
    def setUp(self):

        ##set up code

    def runTest(self):

        #runs test


def suite():
    """
        Gather all the tests from this module in a test suite.
    """
    test_suite = unittest.TestSuite()
    test_suite.addTest(unittest.makeSuite(ConfigTestCase))
    return test_suite

if __name__ == "__main__":
    #So you can run tests from this module individually.
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能正常工作?

ceo*_*com 47

你想用一件套装.所以你不需要调用unittest.main().使用testuit应该是这样的:

#import usertest
#import configtest # first test
import unittest   # second test

class ConfigTestCase(unittest.TestCase):
    def setUp(self):
        print 'stp'
        ##set up code

    def runTest(self):
        #runs test
        print 'stp'

def suite():
    """
        Gather all the tests from this module in a test suite.
    """
    test_suite = unittest.TestSuite()
    test_suite.addTest(unittest.makeSuite(ConfigTestCase))
    return test_suite

mySuit=suite()

runner=unittest.TextTestRunner()
runner.run(mySuit)
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你的回答.为什么我需要调用`unittest.makeSuite`来为*现有*套件添加测试? (2认同)

Jul*_*ian 8

创建加载器和套件的所有代码都是不必要的.您应该编写测试,以便通过使用您最喜欢的测试运行器的测试发现来运行它们.这只是意味着以标准方式命名您的方法,将它们放在可导入的位置(或将包含它们的文件夹传递给跑步者),并继承unittest.TestCase.完成后,您可以使用python -m unittest discover最简单或更好的第三方运动员来发现并运行您的测试.