Python unittest.TestCase对象没有属性'runTest'

时间:2013-09-30 05:45:29

标签: python unit-testing python-3.x python-unittest

以下代码:

import unittest

class Test(unittest.TestCase):
    def test1(self):
        assert(True == True)

if __name__ == "__main__":
    suite = unittest.TestSuite()
    suite.addTest(Test())
    unittest.TextTestRunner().run(suite)

使用Python 3执行它,会引发以下错误:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    unittest.TextTestRunner().run(suite)
  File "/usr/lib/python3.2/unittest/runner.py", line 168, in run
    test(result)
  File "/usr/lib/python3.2/unittest/suite.py", line 67, in __call__
    return self.run(*args, **kwds)
  File "/usr/lib/python3.2/unittest/suite.py", line 105, in run
    test(result)
  File "/usr/lib/python3.2/unittest/case.py", line 477, in __call__
    return self.run(*args, **kwds)
  File "/usr/lib/python3.2/unittest/case.py", line 408, in run
    testMethod = getattr(self, self._testMethodName)
AttributeError: 'Test' object has no attribute 'runTest'

unittest.main()有效。

4 个答案:

答案 0 :(得分:19)

您需要调用TestLoader

if __name__ == "__main__":
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test)
    unittest.TextTestRunner().run(suite)

答案 1 :(得分:8)

您必须指定测试方法名称(test1):

import unittest

class Test(unittest.TestCase):
    def test1(self):
        assert(True == True)

if __name__ == "__main__":
    suite = unittest.TestSuite()
    suite.addTest(Test('test1')) # <----------------
    unittest.TextTestRunner().run(suite)

或者,如果您想在文件中运行所有测试,只需调用unittest.main()即可:

if __name__ == "__main__":
    unittest.main()

答案 2 :(得分:0)

任何TestCase子类的实际测试都在runTest()方法中执行。只需将您的代码更改为:

class Test(unittest.TestCase):
    def runTest(self):
        assert(True == True)

答案 3 :(得分:0)

您可以这样运行它:

python -m unittest <your-module-name>

我不完全理解为什么会起作用。