zoukankan      html  css  js  c++  java
  • excel测试数据导入

    需求背景:测试数据的导入一般在dataprovider中写入对应的测试数据,当参数较多,组合测试或者接口参数测试的测试数据都需要逐一写数据驱动类,数据准备消耗了大量时间。前一篇博客中介绍了对偶测试的小工具,可以通过变量取值情况直接生成excel形式的测试数据,那么本文将介绍将生成的测试数据作为dataprovider导入到测试类中,通过这种方式,可以极大降低重复工作,提高工作效率。

    要把大象装冰箱的三步:
    1、配置文件pom.xml中加入 
            <dependency>
               <groupId>org.apache.poi</groupId>
               <artifactId>poi-ooxml</artifactId>
               <version>3.15</version>
            </dependency>
    ps:你懂的,读取excel这种一定要来个依赖包的,这个poi就提供API给java程序读取Microsoft Office格式档案读和写的功能。版本的话,大家与时俱进~~~。
     
    2、写个函数调用依赖包里面的方法读取excel中的数据。
    package com.netease.vcloud.vod.dataprovider;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.DecimalFormat;
    import org.testng.annotations.DataProvider;
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.apache.poi.ss.usermodel.Cell;
    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.ss.usermodel.WorkbookFactory;
    public class MyDataProvider {
       @DataProvider(name = "MyDataProvider")
        public static Object[][] getTestData() {
                String excelPath    = "D:\\testcase\\input.xlsx";
                String excelSheet   = "test1";
                int rowIndex = 0;
                int colIndex = 0;
                Sheet naviSheet = getSheet(excelPath, excelSheet);
                int iLastRowIndex = naviSheet.getLastRowNum();
                Row row = naviSheet.getRow(0);
                int lastColIndex = row.getLastCellNum();
                Object excelData[][] = new Object[iLastRowIndex+1][lastColIndex];
                for (rowIndex = 0; rowIndex <= iLastRowIndex; rowIndex++) {
                    for (colIndex = 0; colIndex < lastColIndex; colIndex++) {
                        Cell cell = getCell(naviSheet, rowIndex, colIndex);
                        String paramValue = getCellValue(cell);
                        excelData[rowIndex][colIndex] = paramValue;
                    }
                }
                return excelData;
        }
     
        /**
        * @Title: getSheet
        * @Description: Get the sheet from Excel
        * @return: Sheet
        */
        private  static Sheet getSheet(String path, String sheetname){
            InputStream fs = null;
            Sheet naviSheet = null;
            try {
                fs = new FileInputStream(path);
                Workbook wb = WorkbookFactory.create(fs);
                naviSheet = wb.getSheet(sheetname);
            }catch(IOException e)
            {
                e.printStackTrace();
            }catch(InvalidFormatException e)
            {
                e.printStackTrace();
            }
            finally {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
     
            return naviSheet;
        }
     
        /**
        * @Title: getSheet
        * @Description: Get the Cell from Excel
        * @return: Cell
        */
        private static Cell getCell(Sheet sheet, int rowIndex, int columnIndex) {
            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                row = sheet.createRow(rowIndex);
            }
            Cell cell = row.getCell(columnIndex);
            if (cell == null) {
                cell = row.createCell((short) columnIndex);
            }
            return cell;
        }
     
        /**
        * @Title: getCellValue
        * @Description: Get the Cell value from Excel
        * @return: String
        */
        private static String getCellValue(Cell cell) {
            String arg = "";
            DecimalFormat df = new DecimalFormat("#");
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                arg = (cell == null ? "" : cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_NUMERIC:
                Double dvalue = (cell == null ? 0 : cell.getNumericCellValue());
                arg = String.valueOf(dvalue);
                if(arg.matches("\\d+.[0]*"))
                {
                    int endIndex = arg.indexOf(".");
                    arg = arg.substring(0, endIndex);
                }
                if(arg.matches("^((-?\\d+.?\\d*)[Ee]{1}(\\d+))$"))
                {
                    arg = df.format(dvalue);
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                Boolean bool = (cell == null ? false : cell.getBooleanCellValue());
                arg = bool.toString();
                break;
            case Cell.CELL_TYPE_FORMULA:
                arg = (cell == null ? "" : cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_ERROR:
                arg =  (cell == null ? "" : Byte.toString(cell.getErrorCellValue()));
                break;
            case Cell.CELL_TYPE_BLANK:
                arg = "";
                break;
            }
            return arg;
        }
     
    }
    ps:MyDataProvider把excel中的数据一个一个读出来,作为数据驱动哦,源码奉上,简单快捷,也可自己定制需求,按需读取~~~。
     
    3、测试类中导入测试数据
    package com.netease.vcloud.vod.testcase;
     
    import org.testng.annotations.Test;
    import com.netease.vcloud.vod.dataprovider.MyDataProvider;
     
    public class MyTester {
     
        @Test(dataProvider = "MyDataProvider", dataProviderClass = MyDataProvider.class)
        public void runTest(String id, String name, String input, String expected) {
     
                System.out.println("Got one test data.");
                System.out.println("id:["+id+"]");
                System.out.println("name:["+name+"]");
                System.out.println("input:["+input+"]");
                System.out.println("expected:["+expected+"]");
     
        }
    }
    输出:
    excel测试数据导入 - xieyingchunuestc - xieyingchunuestc的博客
      ps:是不是很简单~!再给大家对比一下原有excel中的数据:
    excel测试数据导入 - xieyingchunuestc - xieyingchunuestc的博客
     
     果然一行一行的导进去了!
    机智的盆友会问,对偶测试中有很多无用的数据或者行的标题和头,这怎么处理呢?读取规则自定义呀~写函数定义从生成的测试数据开始读取就可以了,或者心狠手辣的童鞋直接把无用的字段删除,像我一样.....
     
    要结合对偶测试自动生成excel哦,这样才能最大程度上解放劳动力,但需要自己设计的输入数据也完全可以手动敲进去。希望大家用的开心,用的愉快~!
  • 相关阅读:
    Python基础04 字典基本操作
    Python基础03 列表、元组基本操作
    Python基础02 字符串基本操作
    Python基础07 函数作用域、嵌套函数、闭包函数、高阶函数及装饰器的理解
    Python随机数random模块学习,并实现生成6位验证码
    Python与时间相关的time、datetime模块的使用
    Python PIL库安装
    Python中可变对象和不可变对象
    Mac环境下Docker及Splash的安装运行教程
    redis 链表(list)操作
  • 原文地址:https://www.cnblogs.com/a00ium/p/6624919.html
Copyright © 2011-2022 走看看