Java+TestNG+Maven+Excel(使用Excel作为数据驱动)
一、介绍
1、在接口自动化编写中,如何管理测试数据是一个比较重要的,本章主要介绍如何用Excel来作为用例的数据驱动
二、实现
1、在pom.xml文件中引入 Apache POI 和 Apache POI-OOXML 这两个类库,添加在
poi对应的版本号可以参考:https://mvnrepository.com/artifact/org.apache.poi/poi
poi-ooxml对应的版本号可以参考:https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml
<dependency> <groupId>org.apache.poigroupId> <artifactId>poiartifactId> <version>4.1.0version> dependency> <dependency> <groupId>org.apache.poigroupId> <artifactId>poi-ooxmlartifactId> <version>4.1.0version> dependency>
2、读取Excel中的数据
Excel文件名:接口自动化测试.xlsx
存放路径:D:\\接口自动化测试.xlsx 对应的sheet名:测试用例
读取Excel文件内容的代码:
package com.huaxi.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * @title: * @author: 2021/12/2814:08 * @date: 2021/12/2814:08 */ public class ExcelUtils { //private static XSSFCell cell; //private static XSSFRow row; //private static XSSFSheet sheet; //private static XSSFWorkbook workbook; //指定要操作的excel文件的路径及sheet名称 //public static void setExcelFile(String path,String sheetName) throws Exception{ // try { // FileInputStream file = new FileInputStream(path); // workbook = new XSSFWorkbook(file); // sheet = workbook.getSheet(sheetName); // } catch (Exception e) { // e.printStackTrace(); // } //} //读取excel文件指定单元格数据(此方法只针对.xlsx后辍的Excel文件) public static String getCellData(String excelFilePath,String sheetName,int rowNum,int colNum) throws Exception{ //声明一个file文件对象 File file = new File(excelFilePath); //创建一个输入流 FileInputStream in = new FileInputStream(file); //声明workbook对象 Workbook workbook = null; //判断文件扩展名 String fileExtensionName = excelFilePath.substring(excelFilePath.indexOf(".")); if(fileExtensionName.equals(".xlsx")){ workbook = new XSSFWorkbook(in); }else { workbook = new HSSFWorkbook(in); } //获取sheet对象 Sheet sheet = workbook.getSheet(sheetName); //获取行对象 Row row = sheet.getRow(rowNum); //获取列对象 Cell cell = row.getCell(colNum); //获取指定行+列的数据 String rowcoldata = getCellFormatValue(cell).toString(); return rowcoldata; } //获取指定行的测试数据 public static MapgetRowData(String excelFilePath,String sheetName,int rowNum) throws Exception{ //声明一个file文件对象 File file = new File(excelFilePath); //创建一个输入流 FileInputStream in = new FileInputStream(file); //声明workbook对象 Workbook workbook = null; //判断文件扩展名 String fileExtensionName = excelFilePath.substring(excelFilePath.indexOf(".")); if(fileExtensionName.equals(".xlsx")){ workbook = new XSSFWorkbook(in); }else { workbook = new HSSFWorkbook(in); } //获取sheet对象 Sheet sheet = workbook.getSheet(sheetName); //获取行对象 Row row = sheet.getRow(rowNum); //获取最后一列 int lastCell = row.getLastCellNum(); //用于map设置key值,自定义 String columns[] = {"rowNumber", "testCaseName", "url", "params", "environment", "caseDescription"}; //List< Map > list = new ArrayList<>(); Mapmap = new HashMap<>(); for (int i=0; i ){ //获取列对象 Cell cell = row.getCell(i); //封装成map map.put(columns[i], getCellFormatValue(cell)); } //将map放入List //list.add(map); return map; } //在EXCEL的执行单元格中写入数据(此方法只针对.xlsx后辍的Excel文件) rowNum 行号,colNum 列号 public static void setCellData(String excelFilePath,String sheetName, int rowNum,int colNum,String Result) throws Exception{ try { //声明一个file文件对象 File file = new File(excelFilePath); //创建一个输入流 FileInputStream in = new FileInputStream(file); Workbook workbook = new XSSFWorkbook(in); Sheet sheet = workbook.getSheet(sheetName); //获取行对象 Row row = sheet.getRow(rowNum); //获取列对象,如果单元格为空,则返回null Cell cell = row.getCell(colNum); if(cell == null){ cell=row.createCell(colNum); cell.setCellValue(Result); }else{ cell.setCellValue(Result); } FileOutputStream out = new FileOutputStream(file); //将内容写入excel中 workbook.write(out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } //从EXCEL文件中获取所有测试数据 public static Object[][] getTestData(String excelFilePath,String sheetName) throws IOException { //声明一个file文件对象 File file = new File(excelFilePath); //创建一个输入流 FileInputStream in = new FileInputStream(file); //声明workbook对象 Workbook workbook = null; //判断文件扩展名 String fileExtensionName = excelFilePath.substring(excelFilePath.indexOf(".")); if(fileExtensionName.equals(".xlsx")){ workbook = new XSSFWorkbook(in); }else { workbook = new HSSFWorkbook(in); } //获取sheet对象 Sheet sheet = workbook.getSheet(sheetName); //获取sheet中数据的行数,行号从0始 int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum(); List
用例层:
package com.huaxi.huaxitest.ImageCloud; import com.alibaba.fastjson.JSONObject; import com.huaxi.base.BaseRequest; import com.huaxi.base.BaseTest; import com.huaxi.base.LoginService; import com.huaxi.extend.MyTestListener; import com.huaxi.service.ImageCloudService; import com.huaxi.util.ExcelUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import java.lang.reflect.Method; @Slf4j @Listeners({MyTestListener.class}) public class MSTestCase extends BaseTest { @Autowired LoginService loginService; @Autowired ImageCloudService imageCloudService; @Autowired BaseRequest baseRequest; private String token; @DataProvider(name="testData") public static Object[][] data(Method method) throws Exception{ return ExcelUtils.getTestData("D:\\接口自动化测试.xlsx","测试用例"); // 通过反射获得函数名称,可以为多个测试方法提供数据驱动 //Object[][] o = new Object[][] {}; // //// 取用例数据集d1Test的全部数据(excel数据源) //if (method.getName().equals("test1")){ // return ExcelUtils.getRowData("D:\\接口自动化测试.xlsx","测试用例",2).get(""); //} } @BeforeMethod public void beforeMethod() { System.out.println("当前类每个测试方法(@Test)之前运行@BeforeMethod"); token = loginService.AppLogin("18683571131"); } /** * @title: * @author: chaowen.li * @date: 2021/12/29 14:24 */ @Test(dataProvider = "testData",description = "影像云首页",groups = {"眉山医院数字影像"}) public void test001(String rowNumber, String testCaseName, String url, String params, String environment, String caseDescription ) throws Exception{ System.out.println("\nurl:" + url + "\n参数:" + params + "\n描述:" + caseDescription); JSONObject json = JSONObject.parseObject(params.toString()); String result = baseRequest.restTemplatePostJson(url, json, token); JSONObject jsonResult = JSONObject.parseObject(result); log.info("\n=======结果=======\n" + result); Assert.assertEquals("操作成功",jsonResult.getString("msg")); Assert.assertEquals("1",jsonResult.getString("code")); } }
执行结果;
三、总结
Excel,数据库,json等等到底该如何取舍呢?