无法在Python中实例化unittest.TestCase的子类
我正在处理一个文本文件。
这个文件里的每一行都是一个测试的名字。
我想要创建这个测试类的实例,但我总是遇到这个错误:
ValueError: no such test method in <class 'login_to_blog'>: runTest
我在这里写的代码是:
test_name = line.replace("\n", "") #name of test file, class, and method _must_ be shared.
module = __import__(test_name)
test_class = getattr(module, test_name)
suite.addTest(test_class())
这是登录博客的代码:
from selenium import selenium
import unittest, time, re
class login_to_blog(unittest.TestCase):
def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 4444, "*chrome", "http://blog/")
self.selenium.start()
def test_login_to_blog(self):
sel = self.selenium
sel.open("/")
sel.type("signin_username", "jim")
sel.type("signin_password", "jones")
sel.click("//input[@value='Signin']")
sel.wait_for_page_to_load("30000")
try: self.failUnless(sel.is_text_present("your blog posts"))
except AssertionError, e: self.verificationErrors.append(str(e))
def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
需要注意的是,这些测试在命令行中单独运行时是成功的。
你有什么想法可以让我在Python代码中手动创建它们并运行吗?
2 个回答
1
很多人以为只要创建一个测试套件,然后添加一个完整的类,基于unittest.TestCase,就能自动运行里面所有以“test*”开头的函数。这是因为unittest.main()会这样做。但实际上,每个TestCase类只会调用一个单独的方法——你可以查看lib/python/unittest/case.py里的unittest.TestCase的源代码。
class TestCase:
def __init__(self, methodName='runTest'):
问题就出在这里,因为基础类TestCase并没有提供“def runTest”的默认实现。如果你想要模拟unittest.main的行为,那么你需要为每一个想要执行的方法创建一个测试类的实例。
test_name = line.replace("\n", "") #name of test file, class, and method _must_ be shared.
module = __import__(test_name)
test_class = getattr(module, test_name)
for method in dir(test_class):
if method.startswith("test"):
suite.addTest(test_class(method))
9
在查看PyUnit套件文档时,它提到:
在创建一个实例时,我们必须指定要运行的测试方法。我们通过在构造函数中传递方法名称来做到这一点:
defaultSizeTestCase = WidgetTestCase("testDefaultSize")
resizeTestCase = WidgetTestCase("testResize")
接下来,我觉得你要找的内容是:
由于创建一个包含多个同名测试函数的TestCase子类是一种常见的做法,unittest模块提供了一个方便的函数叫做makeSuite,它可以构建一个测试套件,包含测试类中的所有测试用例:
suite = unittest.makeSuite(WidgetTestCase,'test')
所以你想要的是:
suite = unittest.makeSuite(test_class, 'test')
result = unittest.TestResult()
suite.run(result)
或者类似的东西。