selenium自动化测试之【数据驱动测试】
数据驱动测试是自动化测试的主流设计模式之一,相同的测试脚本使用不同的测试数据来执行,测试数据和测试行为进行了完全的分离,这样的测试脚本设计模式称为数据驱动。
实施数据驱动测试的步骤:
1.编写测试脚本,脚本需要支持程序对象、文件或者数据库读入测试数据;
2.将测试脚本使用的数据测试数据存入程序对象、文件或者数据库等外部介质中;
3.运行脚本,循环调用存在外部介质的测试数据;
4.验证所有的测试结果是否符合期望的结果。
下面分别使用4种方式实现数据驱动测试
1.使用TestNG进行数据驱动测试
2.使用CSV文件进行数据驱动测试
3.使用Excel文件进行数据驱动测试
4.使用Mysql数据库实现数据的驱动测试
【一、使用TestNG进行数据驱动测试】
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; /**
* @DataProvider注解的使用
* 使用DataProvider提供数据有两种形式:
* 第一种:一种是在测试代码和测试数据放在同一个类中;
* 第二种:把所有的数据提供都单独写在一个类里面,当测试数据比较多时,这种方法利于维护。
*/
public class DataProviderTest { private static WebDriver driver; // @DataProvide 作为数据提供者,提供几组数组,则引用他的test方法就会执行几次
// @DataProvide 注解定义当前方法中的返回值对象作为测试脚本的测试数据集,并将测试数据集命名为searchWords
@DataProvider(name="searchWords")
public static Object[][] words(){
return new Object[][]{{"蝙蝠侠","主演","迈克尔"},{"超人","导演","唐纳"},{"生化危机","编剧","安德森"}};
} //方法中的3个参数分别使用searchWords测试数据集中的每个一维数组中的数据进行赋值,此测试方法会被调用3次
@Test(dataProvider="searchWords")
public void test(String searchWords1, String searchWords2, String SearchResult){
driver.get("http://www.baidu.com");
driver.findElement(By.id("kw")).sendKeys(searchWords1 +" "+ searchWords2);
driver.findElement(By.id("su")).click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(searchWords1 +">>>>" +searchWords2+">>>>"+SearchResult);
//判断搜索结果中是否包含测试数据中期望的关键词
Assert.assertTrue(driver.getPageSource().contains(SearchResult));
driver.quit();
} @BeforeMethod
public void beforeMethod(){
System.setProperty("webdriver.chrome.driver", "e:\\chromedriver.exe");
driver = new ChromeDriver();
}
}
【二、使用CSV文件进行数据驱动测试】
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List; import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; /**
* 测试数据与测试脚本分离的方式
*/
public class DataProviderCSVTest { public static WebDriver driver; @BeforeMethod
public void beforeMethod(){
System.setProperty("webdriver.chrome.driver", "e:\\chromedriver.exe");
driver = new ChromeDriver();
} @DataProvider(name="testData")
public static Object[][] words() throws IOException{
return getTestData("F://testData.csv");
} @Test(dataProvider="testData")
public void test(String searchWord1,String searchWord2,String searchResult){
driver.get("http://www.baidu.com");
driver.findElement(By.id("kw")).sendKeys(searchWord1+""+searchWord2);
driver.findElement(By.id("su")).click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assert.assertTrue(driver.getPageSource().contains(searchResult));
driver.quit();
} //读取CSV文件的方法
public static Object[][]getTestData(String fileName) throws IOException {
//定义一个集合,存csv文件中的数据
List<Object[]> records = new ArrayList<Object[]>();
String record;
BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
//file.readLine(); //跳过表头, 如果不需要表头的话,不要写这句
while((record=file.readLine())!=null){
String fields[] = record.split(",");
records.add(fields); }
file.close(); //定义方法的返回值,将list转换为Object二维数据
Object[][] results = new Object[records.size()][];
//设置二维数每行的值,每行是一个Object对象
for(int i=0;i<records.size();i++){
results[i] = records.get(i);
} return results;
}
}
【三、使用Excel文件进行数据驱动测试】
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; /**
* 使用Excel文件进行数据驱动测试
* 需引入POI jar包
* @author Administrator
*
*/
public class DataProviderExcelTest { public static WebDriver driver;
String url = "http://www.baidu.com"; @DataProvider(name="testData")
public static Object[][] words() throws IOException{
return getTestData("f://","testData.xlsx","Sheet1");
} @BeforeMethod
public void beforeMethod(){
System.setProperty("webdriver.chrome.driver", "e:\\chromedriver.exe");
driver = new ChromeDriver();
} @AfterMethod
public void AfterMethod(){
driver.quit();
} @Test(dataProvider="testData")
public void test(String searchWord1,String searchWord2,String searchResult){
driver.get(url);
driver.findElement(By.id("kw")).sendKeys(searchWord1+" "+searchWord2);
driver.findElement(By.id("su")).click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assert.assertTrue(driver.getPageSource().contains(searchResult));
} //从excel中获取测试数据的方法
public static Object[][] getTestData(String filePath,String fileName,String sheetName) throws IOException{
//声明一个file文件对象
File file = new File(filePath+"\\"+fileName);
//读取文件
FileInputStream in = new FileInputStream(file);
//声明Workbook对象
Workbook workbook = null;
//获取文件的扩展名
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if(fileExtensionName.equals(".xlsx")){
//.xlsx类型文件
workbook = new XSSFWorkbook(in);
}else {
//.xls类型的文件
workbook = new HSSFWorkbook(in);
}
//通过sheetName,生成Sheet对象
Sheet sheet = workbook.getSheet(sheetName);
//读取sheet1中数据的行数,最后一行减去第一行
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum(); //将excel中的数据存在list中
List<Object[]> records = new ArrayList<Object[]>();
//遍历每行数据,去除第一行表头数据,excel的行号与列号都是从0开始
for(int i=1;i<=rowCount;i++){
//获取行对象
Row row = sheet.getRow(i);
//声明一个数组存放读取的行数据,数组大小用getlastCellNum确定
String fields[] = new String[row.getLastCellNum()];
//遍历每列数据
for(int j=0;j<row.getLastCellNum();j++){
//调用getCell与getStringCellValue方法获取excel中单元格中的数据
fields[j] = row.getCell(j).getStringCellValue();
}
records.add(fields);
} // 定义方法的返回值,将list转换为Object二维数据
Object[][] results = new Object[records.size()][];
// 设置二维数每行的值,每行是一个Object对象
for (int i = 0; i < records.size(); i++) {
results[i] = (Object[]) records.get(i);
} return results;
}
}
【四、使用Mysql数据库实现数据的驱动测试】
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List; import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; /**
* 使用Mysql数据库实现数据的驱动测试
*/ public class DataProviderMysqlTest { public WebDriver driver;
String url = "http://www.baidu.com"; @DataProvider(name="testData")
public Object[][] words() throws IOException{
return getTestData("search");
} @BeforeMethod
public void beforeMethod(){
System.setProperty("webdriver.chrome.driver", "e:\\chromedriver.exe");
driver = new ChromeDriver();
} @AfterMethod
public void afterMethod(){
driver.quit();
} @Test(dataProvider="testData")
public void test(String searchWord1,String searchWord2,String searchResult){
driver.get(url);
driver.findElement(By.id("kw")).sendKeys(searchWord1+" "+searchWord2);
driver.findElement(By.id("su")).click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assert.assertTrue(driver.getPageSource().contains(searchResult));
} //获取Mysql数据库中的测试数据
public static Object[][] getTestData(String tableName) throws IOException{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/bbs";
String username = "root";
String password = "123"; List<Object[]> records = new ArrayList<Object[]>();
try {
//加载数据库驱动
Class.forName(driver);
//获取数据库连接
Connection connection = DriverManager.getConnection(url,username,password);
//创建statement对象
Statement statement = connection.createStatement();
//准备sql语句
String sql = "select argument1,argument2,result from " + tableName ;
//用statement对象执行sql语句
ResultSet rs = statement.executeQuery(sql);
//获取ResultSetMetaData对象
ResultSetMetaData reMetaData = rs.getMetaData();
//调用getColumnCount()获取所有字段的数目(列数)
int columnCount = reMetaData.getColumnCount();
while(rs.next()){
String fields[] = new String[columnCount];
int column = 0;
//遍历所有行数据的所有列数据,并存字符数组中
for(int columnIndex = 0; columnIndex < columnCount; columnIndex ++){
fields[column] = rs.getString(columnIndex +1);
column ++;
}
records.add(fields);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)); }
rs.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
// 定义方法的返回值,将list转换为Object二维数据
Object[][] results = new Object[records.size()][];
// 设置二维数每行的值,每行是一个Object对象
for (int i = 0; i < records.size(); i++) {
results[i] = (Object[]) records.get(i);
}
return results;
}
}
selenium自动化测试之【数据驱动测试】的更多相关文章
- Selenium自动化测试之数据驱动及用例管理
Selenium自动化测试之数据驱动及用例管理 一.TestNg注解介绍 @Test:表示一个测试方法,在运行测试用例过程中,会自动运行@Test注解的方法. 例:
- Java&Selenium自动化测试之数据驱动
一.摘要 本片博文以四个方式展示自动化测试的数据驱动,数组.CSV.Excel.Mysql 二.TestNG&Csv&Driven package testNGWithDataDriv ...
- Selenium自动化测试之结果处理
Selenium自动化测试之结果处理 一.断言 断言相当于性能测试中的检查点,常用断言种类很多,具体可以查看断言API:判断预期结果和实际结果是否一致,断言成功,程序继续处理,失败则终止运行,示例如下 ...
- Selenium自动化测试之启动浏览器
Selenium自动化测试之启动浏览器 一.Eclipse新建java工程 1.新建java工程:File->New->Java Project,输入Project name:如AutoT ...
- selenium自动化测试之整合测试报告
selenium自动化测试之整合测试报告 标签(空格分隔): 整合报告 如下截图我们添加一个文件叫做:latest_report.py文件, import time import os import ...
- Selenium自动化测试之基本控件使用
Selenium自动化测试之基本控件使用 1.输入框input: 在Html中样式: <input id="username" type="text"&g ...
- WEB接口测试之Jmeter接口测试自动化 (三)(数据驱动测试) 接口测试与数据驱动
转载:http://www.cnblogs.com/chengtch/p/6576117.html 1简介 数据驱动测试,即是分离测试逻辑与测试数据,通过如excel表格的形式来保存测试数据,用测试脚 ...
- WEB接口测试之Jmeter接口测试自动化 (三)(数据驱动测试)
接口测试与数据驱动 1简介 数据驱动测试,即是分离测试逻辑与测试数据,通过如excel表格的形式来保存测试数据,用测试脚本读取并执行测试的过程. 2 数据驱动与jmeter接口测试 我们已经简单介绍 ...
- python selenium自动化测试之路(1)--分层测试概念、selenium工具介绍
1.分层自动化测试概念 传统的自动化市场更关注产品UI层的自动化测试,而分层的自动化测试倡导产品开发的不同阶段都需要自动化测试 大多公司与研发团队其实是忽略了单元测试与集成测试阶段的自动化测试工作,所 ...
随机推荐
- 2019牛客暑期多校训练营(第七场) - C - Governing sand - 平衡树
5 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 感觉该出14才对,取前k小写成了取前k大. 5 1 5 4 2 5 3 3 5 2 4 5 1 6 5 5 suf=55 res=0 a ...
- 图片,word,Excel等附件上传
@ResponseBody @RequestMapping("/upload") public String upload(HttpServletRequest request, ...
- Vue Login by Google
vue-google-oauth2 来源:https://www.npmjs.com/package/vue-google-oauth2
- 关于python - 更优雅的技巧
枚举 不要这么做: i = 0 for item in iterable: print i, item i += 1 而是这样: for i, item in enumerate(iterable): ...
- Antd-react-mobile项目学习中遇到的问题记录(持续更新)
1.Error:The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use customi ...
- echart 属性设计大全
// 全图默认背景 // backgroundColor: ‘rgba(0,0,0,0)’, // 默认色板 color: ['#ff7f50','#87cefa','#da70d6','#32cd ...
- 入手node
一.安装node(查询使用npm) 二.安装淘宝镜像(查询使用cnpm,安装淘宝镜像之后下载速度会更快) 三.安装相关资料时,在预安装的文件夹使用: shift + 右键, 打开命令行窗口,进入终端
- JavaEE高级-通用Mapper学习笔记
通用 Mapper 笔记 1 引入 1.1作用 替我们生成常用增删改查操作的 SQL 语句. 1.2代码官方发布地址 https://gitee.com/free https://gitee.com/ ...
- js如何判断用户使用的设备类型及平台
前端开发经常遇到需要判断用户的浏览设备,是pc端还是移动端,移动端使用的是什么手机系统?android.ios.ipad.windows phone等等,有时候还需要知道用户浏览页面是在微信中打开还是 ...
- koa2 进阶网站
http://www.ruanyifeng.com/blog/2017/08/koa.html 阮一峰 https://www.itying.com/koa/ koa2中文网 https://blo ...