unittest测试用例代码-一分钟就掌握

定义继承于TestCase类的子类

import unittest

from seleniumimport webdriver

class SearchTests(unittest.TestCase):

setUp()方法

一个测试用例是从setUp()方法开始执行的的,主要是这样的初始化准备:比如创建浏览器实例,访问URL,加载测试数据和打开日志文件等。

1、此方法没有参数,不返回任何值

2、测试执行器每次执行测试方法之前优先执行setUp()方法。

def setUp(self):

# create a new Firefox session

    self.driver = webdriver.Firefox() #创建实例

    self.driver.implicitly_wait(30) #设置properties

    self.driver.maximize_window() #设置properties

# navigate to the application home page

self.driver.get("http://demo.magentocommerce.com/")

添加一个新的测试方法test_search_by_category()

通过分类来搜索产品,然后校验返回的产品的数量是否正确,

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(3, len(products))

tearDown()方法

TestCase类也会在测试执行完成之后调用tearDown()方法来清理所有的初始化值。一旦测试被执行,在setUp()方法中定义的值将不再需要,所以最好的做法是在测试执行完成的时候清理掉由setUp()方法初始化的数值。

def tearDown(self):

    # close the browser window

    self.driver.quit()

运行测试

在测试用例中添加对main方法的调用。传递verbosity参数以便使详细的测试总量展示在控制台。

if __name__ =='__main__':

    unittest.main(verbosity=2)

资料来源:Selenium自动化测试:基于Python语言

你可能感兴趣的:(unittest测试用例代码-一分钟就掌握)