当一个类中有多条用例,我们在执行的时候每执行一条用例就要重新打开一次浏览器操作,例如下:
start
test1
quit
start
test2
start
若我们使用@classmethod装饰器,就只需要打开一次浏览器,执行完用例后再关闭,例如下:
start
test1
test2
quit
代码:
from selenium import webdriver
import unittest,time
from selenium.webdriver.support import expected_conditions as EC
class Test1(unittest.TestCase):
#测试类,是多个测试用例的集合,可以把一些相同的操作写成一个类
@classmethod
def setUpClass(cls):
cls.driver=webdriver.Chrome()
cls.driver.get("http://www.cnblogs.com/linbao/")
time.sleep(2)
def test_01(self):
u'''验证元素存在:博客园'''
locator = ("id", "blog_nav_sitehome")
text = u"博客园"
time.sleep(2)
result = EC.text_to_be_present_in_element(locator, text)(self.driver)
time.sleep(2)
self.assertTrue(result)
def test_02(self):
u'''验证元素存在:首页'''
locator = ("id", "blog_nav_myhome")
text = u"首页"
time.sleep(2)
result = EC.text_to_be_present_in_element(locator, text)(self.driver)
time.sleep(2)
self.assertTrue(result)
@classmethod
def tearDownClass(cls):
# 后置操作
time.sleep(2)
cls.driver.quit()
if __name__=="__main__":
#运行主函数
unittest.main()