测试固件分为两种情况,一种是每执行一个用例的时候,测试固件都会被执行到。一种是不管有多少测试用例,测试固件只执行一次。
1.测试固件每次均执行
unittest单元测试框架提供了setUp和teardown的测试固件。执行方式如下:
import unittest class BaiduTest(unittest.TestCase): def setUp(self): print('start') def tearDown(self): print('end') def test_baidu_so(self): print('测试用例执行') if __name__ == '__main__': unittest.main(verbosity=2)
例子:
from selenium import webdriver import unittest class BaiduTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.maximize_window() self.driver.get('http://www.baidu.com') self.driver.implicitly_wait(30) def tearDown(self): self.driver.quit() def test_baidu_news(self): self.driver.find_element_by_link_text('新').click() def test_baid_taps(self): self.driver.find_element_by_link_text('地图').click() if __name__ == '__main__': unittest.main(verbosity=2)
2.测试固件只执行一次
import unittest class UiTest(unittest.TestCase): @classmethod def setUpClass(cls): print('start') @classmethod def tearDownClass(cls): print('end') def test_001(self): print("第一个测试用例") def test_002(self): print("第二个测试用例") if __name__ == '__main__': unittest.main(verbosity=2)
例子:
from selenium import webdriver import unittest class UiTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome() cls.driver.maximize_window() cls.driver.get('http://www.baidu.com') cls.driver.implicitly_wait(30) @classmethod def tearDownClass(cls): cls.driver.quit() def test_001(self): self.driver.find_element_by_link_text("新闻").click() self.driver.get("http://www.baidu.com") def test_002(self): self.driver.find_element_by_link_text("地图").click() self.driver.get("http://www.baidu.com") if __name__ == '__main__': unittest.main()