Selenium Python 如何使用unittest.TestCase的assertEqual方法 “<class 'unittest.case.TestCase'>中没有此测试方法”
我想在普通的类里使用assertEqual这个方法,但我无法从unittest.TestCase中调用这个方法。
class MyPages(unittest.TestCase):
@classmethod
def setUpClass(cls):
basetest.BaseTest().open_browser('firefox')
basetest.BaseTest().login()
def testCreateFolder(self):
print "111111111"
def testCreateFolder1(self):
print "222222222"
@classmethod
def tearDownClass(cls):
basetest.BaseTest().close_browser()
在我的BaseTest里,我想用文本断言来进行登录。
class BaseTest():
def open_browser(self, browser):
self.driver = config.browser[browser]
global driver
driver = self.driver
driver.get(config.url)
def login(self):
# Go to authorisation page
driver.find_element_by_xpath(link.header["Login_button"]).click()
# Get text from LOGIN label and assert it with expected text
login_text = driver.find_element_by_xpath(link.author_popup["Login_label"])
login_text.get_attribute("text")
print login_text.text
unittest.TestCase().assertEqual(1, 1, "helllllllo")
unittest.TestCase().assertEqual(login_text.text, text.author_popup["Login"],
"Wrong label on log in auth popup. Expected text:")
结果我得到了以下内容:
Error
Traceback (most recent call last):
File "D:\python\PD_Tests\pages\my_pages.py", line 17, in setUpClass
basetest.BaseTest().login()
File "D:\python\PD_Tests\tests\basetest.py", line 25, in login
unittest.TestCase().assertEqual(1, 1, "helllllllo")
File "C:\Python27\lib\unittest\case.py", line 191, in __init__
(self.__class__, methodName))
ValueError: no such test method in <class 'unittest.case.TestCase'>: runTest
如果我的类不是unittest.TestCase,我能在我的方法里使用assertEqual方法吗?
2 个回答
1
有没有什么特别的原因不让BaseTest
从unittest.TestCase
继承呢?
我的解决方案是创建一个SeleniumTestcase
类,这个类从unittest.TestCase
继承,并提供setUp
和tearDown
这两个方法。只要确保在创建SeleniumTestcase
实例时,config
是已知的就可以了。
1
我觉得有办法可以实现你想要的,不过这有点像是变通的方法。
TestCase
类的构造函数需要一个方法名作为参数,这个参数的默认值是"runTest"
。这个构造函数的说明大致是这样的:
创建一个类的实例,当执行时会使用指定的测试方法。如果实例没有这个名字的方法,就会抛出一个ValueError错误。
希望这能帮助你理解你看到的错误信息。
如果你只是想创建一个TestCase
来使用一些断言方法,你可以传入其他方法的名字,比如__str__
。这样就能绕过构造函数中的检查:
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from unittest import TestCase
>>> t = TestCase("__str__")
>>> t.assertEqual(3, 5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\unittest\case.py", line 511, in assertEqual
assertion_func(first, second, msg=msg)
File "C:\Python27\lib\unittest\case.py", line 504, in _baseAssertEqual
raise self.failureException(msg)
AssertionError: 3 != 5
>>> t.assertEqual(3, 3)
>>>
只要你不尝试运行你的TestCase,这应该就没问题。