unittest- TypeError: this constructor takes no arguments

unittest- TypeError: this constructor takes no arguments

我 运行 所有测试来自 class TestNothing 使用 unittest.TestSuite().

我的__init__.py是:

import unittest
from .test_nothing import TestNothing


def suite():
    """
    Define suite
    """
    test_suite = unittest.TestSuite()
    test_suite.addTests([
        unittest.TestLoader().loadTestsFromTestCase(TestNothing),
    ])
    return test_suite


if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(suite())

我的test_nothing.py是:

import unittest


class TestNothing:
    def test_0010_test_nothing(self):
        self.assertEqual(200, 200)


def suite():
    "Test suite"
    test_suite = unittest.TestSuite()
    test_suite.addTests(
        unittest.TestLoader().loadTestsFromTestCase(TestNothing)
    )
    return test_suite


if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(suite())

当 运行 python test_nothong.py 是:

时出现以下错误
Traceback (most recent call last):
  File "test_nothing.py", line 19, in <module>
    unittest.TextTestRunner(verbosity=2).run(suite())
  File "test_nothing.py", line 13, in suite
    unittest.TestLoader().loadTestsFromTestCase(TestNothing)
  File 

"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 56, in loadTestsFromTestCase
        loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
    TypeError: this constructor takes no arguments

确实,实际上 TestNothing 的构造函数不带参数...而且必须。 我建议您使测试 class TestNothing 继承自 unittest.TestCase。像这样,你的 class 的 Ctor 将从带参数的构造函数 unittest.TestCase 继承。

import unittest
class TestNothing(unittest.TestCase):
    def test_0010_test_nothing(self):
        self.assertEqual(200, 200)

你还可以更进一步,按照这个linkpython unittest 25.3.1