Python unittest.TestCase 对象没有属性“runTest”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19087189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python unittest.TestCase object has no attribute 'runTest'
提问by Jingguo Yao
For the following code:
对于以下代码:
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)
Using Python 3 to execute it, the following error is raised:
使用 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'
But unittest.main()
works.
但是unittest.main()
有效。
采纳答案by Janne Karila
You need to invoke a TestLoader
:
您需要调用一个TestLoader
:
if __name__ == "__main__":
suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test)
unittest.TextTestRunner().run(suite)
回答by Sajjan Singh
The actual test for any TestCase
subclass is performed in the runTest()
method. Simply change your code to:
任何子TestCase
类的实际测试都在runTest()
方法中执行。只需将您的代码更改为:
class Test(unittest.TestCase):
def runTest(self):
assert(True == True)
回答by falsetru
You have to specify the test method name (test1
):
您必须指定测试方法名称 ( 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)
Or, if you want to run all tests in the file, Just calling unittest.main()
is enough:
或者,如果您想运行文件中的所有测试,只需调用即可unittest.main()
:
if __name__ == "__main__":
unittest.main()