37

我有两个要在测试套件中一起运行的测试用例(两个不同的文件)。我可以通过“正常”运行 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"

这是我设置的测试用例的示例

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()

我该怎么做才能正确完成这项工作?

4

4 回答 4

54

你想使用测试服。所以你不需要调用 unittest.main()。testsuit的使用应该是这样的:

#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)
于 2012-08-17T18:46:59.007 回答
8

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

于 2012-08-17T18:44:30.963 回答
2

如果您尝试手动收集TestCases,这很有用unittest.loader.findTestCases()::

# Given a module, M, with tests:
mySuite = unittest.loader.findTestCases(M)
runner = unittest.TextTestRunner()
runner.run(mySuit)
于 2013-11-25T17:08:45.383 回答
1

我假设您指的是针对合并这两个测试的模块运行 python-unit 测试。如果您为该模块创建测试用例,它将起作用。子类unittest.TestCase化并进行一个以“test”开头的简单测试。

例如

class testall(unittest.TestCase):

    def test_all(self):           
        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"

if __name__ == "__main__": 
      unittest.main()
于 2012-08-17T19:20:12.763 回答