美文网首页
unittest单元测试框架

unittest单元测试框架

作者: 心无旁骛_ | 来源:发表于2018-05-29 10:55 被阅读23次

2.7官方文档
3.6官方文档

一、【使用 unittest 的标准流程为】

1.从 unittest.TestCase 派生一个子类
2.在类中定义各种以 “test_” 打头的方法
3.通过 unittest.main() 函数来启动测试

@python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# coding=utf-8
'''
Project:百度搜索测试用例
'''

from selenium import webdriver
import unittest, time

class BaiduTest(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)  # 隐性等待时间为30秒
        self.base_url = "https://www.baidu.com"

    def test_baidu(self):
        driver = self.driver
        driver.get(self.base_url + "/")
        driver.find_element_by_id("kw").clear()
        driver.find_element_by_id("kw").send_keys("unittest")
        driver.find_element_by_id("su").click()
        time.sleep(3)
        title = driver.title
        self.assertEqual(title, u"unittest_百度搜索")

    def tearDown(self):
        self.driver.quit()


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

二、 setUp() 和 tearDown()

在unittest 里,它们提供了为测试进行准备和扫尾工作。

setUp() 方法用于在执行每条测试项前,被调用,tearDown() 方法用于在每条测试项前先后,被调用。

三、setUpClass() 和 tearDownClass()

用于全程只调用一次 setUp/tearDown,配合 @classmethod 装饰器使用。比如:
@python
import unittest
class simple_test(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.foo = list(range(10))

    def test_1st(self):
        self.assertEqual(self.foo.pop(),9)

    def test_2nd(self):
        self.assertEqual(self.foo.pop(),8)

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

运行结果显示依然是全部通过,说明这次在全部测试项被调用前只调用了一次 setUpClass()

四、 setUpModule() 和 tearDownModule() 函数

这个是函数,与TestCase同级

@python
import unittest

def setUpModule():
    pass

class BaiduTest(unittest.TestCase):

注意:tearDown() 仅在 setUp() 成功执行的情况下才会执行,并一定会被执行。

参考链接
参考链接

相关文章

网友评论

      本文标题:unittest单元测试框架

      本文链接:https://www.haomeiwen.com/subject/hrpojftx.html