类级别的setUp()方法与tearDown()方法
在实操(一)的例子中,通过setUp()方法为每个测试方法都创建了一个Chrome实例,并且在每个测试方法执行结束后要关闭实例。是不是觉得有个多余了!能否让各个测试方法共用一个Chrome实例,而不用每次都创建一个新的实例呢?肯定可以的,unittest为我们提供了明路。可以通过用setUpClass()方法和tearDownClass()方法及@classmethod标识来实现。这两个方法使我们可以在类级别来初始化数据,替代了方法级别的初始化,这样各个测试方法就可以共享这些初始化数据。在前面的例子中,代码修改为调用setUpClass()方法和tearDownClass()方法并且加上@classmethod标识。
import unittest from selenium import webdriver from time import sleep class BaiduSearchTest(unittest.TestCase): @classmethod def setUpClass(cls): #create a new Chrome session cls.driver = webdriver.Chrome() cls.driver.implicitly_wait(30) cls.driver.maximize_window() cls.driver.get('https://www.baidu.com') def test_search_python(self): #get the search textbox search_textbox = self.driver.find_element_by_id('kw') search_textbox.clear() #enter search keyword search_textbox.send_keys("python") #get the and seacrh button and click search_button = self.driver.find_element_by_id('su') search_button.click() #add assert sleep(2) tag = self.driver.find_element_by_link_text("PyPI").text self.assertEqual('PyPI',tag) def test_search_selenium(self): search_textbox = self.driver.find_element_by_id('kw') search_textbox.clear() search_textbox.send_keys("python") search_button = self.driver.find_element_by_id('su') search_button.click() sleep(2) tag = self.driver.find_element_by_link_text("Selenium Remote Control").text self.assertIn('Selenium',tag) def tearDownClass(cls): #close the browser window cls.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)