认识unittest

单元测试框架提供功能如下:

  1. 提供用例组织和执行
  2. 提供丰富的断言方法
  3. 提供丰富的日志

重要概念:

  • Test Case
    是最小的测试单元,用于检查特定输入集合的特定返回值。
  • Test Suite
    测试套件是测试用例、测试套件或两者的集合,用于组装一组要运行的测试。
  • Test Runner
    用于协调测试的执行并向用户提供结果
  • Test Fixture
    代表执行一个或多个测试所需的环境准备,以及关联的清理动作

unittest框架流程:

1.写好TestCase(测试用例)
2.由TestLoder加载TestCase到TestSuite(测试用例集)
3.然后TextTestRunner来运行TestSuite,然后把结果保存在报告中。

断言方法

在执行测试用例的过程中,最终测试用例执行成功与否,是通过测试得到的实际结果与预期结果进行比较得到的。

方法 检查 方法 检查
assertEqual(a,b) a==b assertIsNone(x) x is None
assertNotEqual(a,b) a!=b assertIsNotNone(x) x is not None
assertTrue(x) bool(x) is True assertIn(a,b) a in b
assertFalse(x) bool(x) is False assertNotIn(a,b) a not in b
assertIs(a,b) a is b assertIsInstance(a,b) isinstance(a,b)
assertIsNot(a,b) a is not b assertNotIsInstance(a,b) not isinstance(a,b)

测试模型

线性测试

  • 概念
    通过录制或编写对应应用程序的操作步骤产生的线性脚本。
  • 优点
    每个脚本相对于独立,且不产生其他依赖和调用,任何一个测试用例脚本拿出来都可以单独执行。
  • 缺点
    开发成本高,用例之间存在重复的操作

模块化驱动测试

  • 概念
    将重复的操作独立成共享模块(函数、类),当用例执行过程中需要用到这一模块操作的时候被调用。
  • 优点
    由于最大限度消除了重复,从而提高了开发效率和提高测试用例的可维护性
  • 缺点
    虽然模块化的步骤相同,但是测试数据不同

数据驱动测试

  • 概念
    它将测试中的测试数据和操作分离,数据存放在另外一个文件中单独维护,通过数据的改变从而驱动自动化测试的执行,最终引起测试结果的改变。
  • 优点
    通过这种方式,将数据和重复操作分开,可以快速增加相似测试,完成不同数据情况下的测试。
  • 缺点
    数据的准备工作

实战


├── test_case			用例文件夹
│   └── test_baidu.py		测试用例
├── test_report			测试报告文件夹
├── util			工具类
│   └── HTMLTestRunnerCN.py	汉化报告
└── Run_test.py			启动

test_baidu.py	测试用例

from selenium import webdriver
import unittest
import time
class TestBaidu(unittest.TestCase):
    def setUp(self):
        self.driver=webdriver.Chrome()
        self.driver.implicitly_wait(10)
        self.driver.get('https://www.baidu.com')
        time.sleep(3)
		#定义测试用例,名字以test开头,unittest会自动将test开头的方法放入测试用例集中。
    def test_baidu(self):
        self.driver.find_element_by_id('kw').send_keys('greensunit')
        self.driver.find_element_by_id('su').click()
        time.sleep(2)
        title=self.driver.title
        self.assertEqual(title,'greensunit_百度搜索')

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

Run_test.py			启动

import unittest,time
from util.HTMLTestRunnerCN import HTMLTestRunner
test_dir='./test_case'
discover=unittest.defaultTestLoader.discover(test_dir,pattern='test*.py')

if __name__ == '__main__':
    report_dir='./test_report'
    now=time.strftime('%Y-%m-%d %H-%M-%S')
    report_name=report_dir+'/'+now+'_result.html'
    with open(report_name,'wb') as f:
        runner=HTMLTestRunner(stream=f,title='百度搜索报告',description='百度搜索自动化测试报告总结')
        runner.run(discover)

image

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/greensunit/p/14679013.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!