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 Map getRowData(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<>();
        Map map = 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 records = new ArrayList();
        //读取数据(省略第一行表头)
        for(int i=1; i<=rowCount; i++){
            //获取行对象
            Row row = sheet.getRow(i);
            //声明一个数组存每行的测试数据
            String[] fields = new String[row.getLastCellNum()];
            for(int j=0; j){
                //获取每个单元格的数据
                Cell cell = row.getCell(j);
                fields[j] = getCellFormatValue(cell).toString();
                }
            records.add(fields);
        }
        //将list转为Object二维数据
        Object[][] results = new Object[records.size()][];
        //设置二维数据每行的值,每行是一个object对象
        for(int i=0; i){
            results[i]=records.get(i);
        }
        return results;
    }

    //格式化数值类型
    public static Object getCellFormatValue(Cell cell){
        Object cellValue = null;
        /**
         * getCellTypeEnum()方法是枚举类型,用于判断单元格值类型,有以下五种格式:
         *     _NONE(-1),
         *     NUMERIC(0),
         *     STRING(1),
         *     FORMULA(2),
         *     BLANK(3),
         *     BOOLEAN(4),
         *     ERROR(5);
         */
        switch(cell.getCellType()){
            case STRING:
                cellValue = cell.getStringCellValue();
                break;
            case NUMERIC:
                /**如果是数字类型转换成数字类型,但是初始化数字加的.0,因此可以转换成int类型去掉.0
                 * cell.getNumericCellValue()
                 */
                cellValue = new Double(cell.getNumericCellValue()).intValue();
                break;
            case BOOLEAN:
                break;
            case BLANK:
                break;
            case FORMULA:
                break;
            case ERROR:
                break;
            default:
                break;
        }
        return cellValue;
    }

    //public static int getLastColumnNum(){
    //    //返回数据文件最后一列的列号,如果有12列则返回11
    //    return sheet.getRow(0).getLastCellNum()-1;
    //}
}

 用例层:

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等等到底该如何取舍呢?