java結合testng,利用excel做數據源的數據驅動實例


數據驅動部分,是自動化測試常用部分,也是參數化設計的重要環節,前面分享了,mysql、yaml做數據源,那么再來分享下excel做數據驅動

思路:

先用POI讀取excel。解析讀取數據,返回list,返回Object[][]即可

工具類文件:

讀取excel,返回map對象list集合

ReadExcelUtil.java

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 讀取excel,返回map對象list集合
 *
 * @author longrong.lang
 */
public class ReadExcelUtil {


    /**
     * 讀取excel操作
     *
     * @param filePath
     * @return:讀取excel,返回map對象集合
     */
    public static List<Map<String, String>> getExcuteList(String filePath) {
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String, String>> list = null;
        String cellData = null;
        String columns[] = {"name", "method", "value","備注"};
        wb = readExcel(filePath);
        if (wb != null) {
            //用來存放表中數據
            list = new ArrayList<Map<String, String>>();
            //獲取第一個sheet
            sheet = wb.getSheetAt(0);
            //獲取最大行數
            int rownum = sheet.getPhysicalNumberOfRows();
            //獲取第一行
            row = sheet.getRow(0);
            //獲取最大列數
            int colnum = row.getPhysicalNumberOfCells();
            for (int i = 1; i < rownum; i++) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                row = sheet.getRow(i);
                if (row != null) {
                    for (int j = 0; j < colnum; j++) {
                        cellData = (String) getCellFormatValue(row.getCell(j));
                        map.put(columns[j], cellData);
                    }
                } else {
                    break;
                }
                list.add(map);
            }
        }
        return list;
    }


    /**
     * 判斷excel文件的類型
     *
     * @param filePath
     * @return
     */
    public static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    public static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            //判斷cell類型
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC: {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                }
                case Cell.CELL_TYPE_FORMULA: {
                    //判斷cell是否為日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        //轉換為日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    } else {
                        //數字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }

}

然后把解析出來的list轉換成Object[][]類型的數據,且結合在@DataProvider中。

import org.testng.annotations.DataProvider;

import java.util.List;
import java.util.Map;

public class ExcelDataHeleper {
    

    @DataProvider
    public Object[][] dataMethod(){
        List<Map<String, String>> result = ReadExcelUtil.getExcuteList("D:\\data.xls");
        Object[][] files = new Object[result.size()][];
        for(int i=0; i<result.size(); i++){
            files[i] = new Object[]{result.get(i)};
        }        
        return files;
    }
    

}

再通過測試文件來測試一下:

import org.testng.annotations.Test;

import java.util.Map;

public class TestDataUtil extends ExcelDataHeleper {


    @Test(dataProvider="dataMethod")
    public void testmethod1(Map<?, ?> param){
        System.out.println(param.get("name")+"\t"+param.get("method")+"\t"+param.get("value"));
    }


}

運行結果:

[TestNG] Running:
  C:\Users\Administrator\.IntelliJIdea2018.2\system\temp-testng-customsuite.xml
輸入框	id	kw
百度一下	id	su
退出	name	tj_logout
2018年11月15日14點41分	2018/11/15 14:42:31	腳本
退出	name	tj_logout

===============================================
Default Suite
Total tests run: 5, Failures: 0, Skips: 0
===============================================

Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8

Process finished with exit code 0

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM