Unittest学习(三)--------类级别的setUp()方法和tearDown()方法

         在前面的例子中,我们通过setUp()方法为每个测试方法都创建了一个Firefox实例,并且在每个测试方法执行结束后都要关闭实例。能否让各个测试方法共用一个Firefox实例,而不要每次都创建一个新的实例呢?这可以通过使用setUpClass()方tearDownClass()方法及@classmethod标识来实现。这两个方法使我们可以在类级别来初始化数据,替代了方法级别的初始化,这样各个测试方法就可以共享这些初始化数据。在下面的例子中,代码修改为调用setUpClass()方法和tearDownClass()方法并且加上@classmethod标识。

import unittest
from selenium import webdriver

class SearchTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # create a new Firefox session
        cls.driver = webdriver.Firefox()
        cls.driver.implicitly_wait(30)
        cls.driver.maximize_window()

        # navigate to the application home page
        cls.driver.get("http://demo.magentocommerce.com/")
        cls.driver.title

    def test_search_by_category(self):
        # get the search textbox
        self.search_field = self.driver.find_element_by_name("q")
        self.search_field.clear()

        # enter search keyword and submit
        self.search_field.send_keys("phones")
        self.search_field.submit()

        # get all the anchor elements which have product names
# displayed currently on result page using
        # find_elements_by_xpath method
        products = self.driver.find_elements_by_xpath
          ("//h2[@class='product-name']/a")
        self.assertEqual(2, len(products))

    def test_search_by_name(self):
        # get the search textbox
        self.search_field = self.driver.find_element_by_name("q")
        self.search_field.clear()
      
        # enter search keyword and submit
        self.search_field.send_keys("salt shaker")
        self.search_field.submit()
      
        # get all the anchor elements which have product names
        # displayed currently on result page using
        # find_elements_by_xpath method
        products = self.driver.find_elements_by_xpath
          ("//h2[@class='product-name']/a")
        self.assertEqual(1, len(products))

    @classmethod
    def tearDownClass(cls):
        # close the browser window
        cls.driver.quit()

    if __name__ == '__main__':
         unittest.main()

       运行这个测试将看到仅创建一个Firefox实例,所有的测试都用同一个实例。

你可能感兴趣的:(selenium)