Python unit test: testcase class with own constructor fails in standard library
本问题已经有最佳答案,请猛点这里访问。
我有这个简单的vanilla单元测试,只要我省略了构造函数,它就会按预期工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import sys import unittest class Instance_test(unittest.TestCase): def __init__(self): super(Instance_test, self).__init__() self.attribute ="new" def test_something(self): pass def test_other(self): self.assertTrue(True) pass def setUp(self): pass def tearDown(self): pass def suite(): return unittest.makeSuite(Instance_test,"test") def main(): runner = unittest.TextTestRunner(sys.stdout) runner.run(suite()) if __name__ =="__main__": main() |
使用构造函数获取此回溯:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Traceback (most recent call last): File"f:\gt\check.py", line 31, in main() File"f:\gt\check.py", line 28, in main runner.run(suite()) File"f:\gt\check.py", line 24, in suite return unittest.makeSuite(Instance_test,"test") File"C:\Python34\lib\unittest\loader.py", line 374, in makeSuite testCaseClass) File"C:\Python34\lib\unittest\loader.py", line 70, in loadTestsFromTestCase loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) File"C:\Python34\lib\unittest\suite.py", line 24, in __init__ self.addTests(tests) File"C:\Python34\lib\unittest\suite.py", line 60, in addTests for test in tests: TypeError: __init__() takes 1 positional argument but 2 were given |
有什么不对,我怎么能拥有一个由不同的test_xxx方法共享的中心属性?
我会使用unittest.TestCase的setUp()和tearDown()方法而不是init。 除了使用
它正在发生,因为
1 2 3 4 5 | class Instance_test(unittest.TestCase): def __init__(self, *args, **kwargs): super(Instance_test, self).__init__(*args, **kwargs) self.attribute ="new" |
此外,当
1 2 3 4 | class Instance_test(unittest.TestCase): def setUp(self): self.attribute = 'new' |
只需将一个名为
1 2 3 4 5 6 7 | class Instance_test(unittest.TestCase): def __init__(self, methodName='runTest'): super(Instance_test, self).__init__(methodName=methodName) self.attribute ="new" ... |
base
1 2 3 4 | class TestCase(object): def __init__(self, methodName='runTest'): ... |
正如您所看到的,它需要一个额外的