unittest測試框架詳談及實操(二)

類級別的setUp()方法與tearDown()方法html

  在實操(一)的例子中,經過setUp()方法爲每一個測試方法都建立了一個Chrome實例,而且在每一個測試方法執行結束後要關閉實例。是否是以爲有點多餘!可否讓各個測試方法共用一個Chrome實例,而不用每次都建立一個新的實例呢?確定能夠的,unittest爲咱們提供了明路。能夠經過用setUpClass()方法和tearDownClass()方法及@classmethod標識來實現。這兩個方法使咱們能夠在類級別來初始化數據,替代了方法級別的初始化,這樣各個測試方法就能夠共享這些初始化數據。在前面的例子中,代碼修改成調用setUpClass()方法和tearDownClass()方法而且加上@classmethod標識。python

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("selenium") 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) @classmethod def tearDownClass(cls): #close the browser window
 cls.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)

  運行這個測試將看到僅建立一個Chrome實例,全部測試方法都用同一個實例。web

  要了解更多關於@classmethod標識的信息參考:session

  https://docs.python.org/3.6/library/functions.html#classmethod測試

相關文章
相關標籤/搜索