数据驱动测试之—— Excel+TestNG

时间:2023-03-09 03:11:34
数据驱动测试之—— Excel+TestNG

对于利用Webdriver做自动化的童鞋,对于如何将元素或者输入数据如何和编码分离都应该不会太陌生,本着一边学习一边分享的心态,大概总结了一下关于利用CSV、XML以及Excel来存放数据,然后在结合TestNG来执行数据驱动测试。

需要的Jar包文件:

poi-3.11-20141221.jar

poi-ooxml-3.11-20141221.jar

poi-ooxml-schemas-3.11-20141221.jar

xmlbeans-2.6.0.jar

下面是关于Excel+TestNG进行数据驱动的代码:

package com.util.datadriver;

import java.io.File;
import java.io.FileInputStream;
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.testng.annotations.DataProvider;
import org.testng.annotations.Test; /**
*
* 利用TestNG和Excel(poi)实现数据的驱动
*
* 需要导入额jar包: poi-3.11-20141221.jar、 poi-ooxml-3.11-20141221.jar、
* poi-ooxml-schemas-3.11-20141221.jar、 xmlbeans-2.6.0.jar
*/ public class DataProviderExcel { @DataProvider(name = "excelData")
public static Object[][] excelData() throws Exception { return getExcelData("date", "excelData.xlsx", "testSheet1"); } @Test(dataProvider = "excelData")
public void testExcelData(String input1, String input2, String input3) { System.out.println(input1);
System.out.println(input2);
System.out.println(input3); } @SuppressWarnings("resource")
public static Object[][] getExcelData(String filePath, String fileName,
String sheetName) throws Exception { Workbook workbook = null; File file = new File(filePath + "/" + fileName);
FileInputStream fis = new FileInputStream(file); String type = fileName.substring(fileName.indexOf(".")); // Excel2007 以后的格式为.xlsx的Excel文件,需要调用XSSFWorkbook
// Excel2007以前版本的格式为.xls的Excel文件,需要调用HSSFWorkbook if (type.equals(".xlsx")) { workbook = new XSSFWorkbook(fis); } else if (type.equals(".xls")) { workbook = new HSSFWorkbook(fis);
} Sheet sheet = workbook.getSheet(sheetName); // 获得最后一行的行数
int lastRowCount = sheet.getLastRowNum();
// 获得第一行的行数
int firstRowCount = sheet.getFirstRowNum();
// Excel行数从第0行开始
int sumRowCount = lastRowCount - firstRowCount + 1; List<Object[]> list = new ArrayList<Object[]>(); // 获取每行的行对象,第一行为信息栏,不计入,所以从1开始
for (int i = 1; i < sumRowCount; i++) {
Row row = sheet.getRow(i);
// 获得一行中最后单元格的count
int lastCellCount = row.getLastCellNum(); // 定义一个数组来存放cell中值,根据cell的长度来定义数组的长度
String[] fileds = new String[lastCellCount]; for (int j = 0; j < lastCellCount; j++) {
String cellValue = row.getCell(j).getStringCellValue();
fileds[j] = cellValue;
}
list.add(fileds);
} fis.close(); // 定义一个object[][] 的二维数组,存放list中的值
Object[][] results = new Object[list.size()][];
// 设置二维数组每行的值,
for (int a = 0; a < list.size(); a++) { results[a] = list.get(a); } return results; } }