Testng+DataProvider+自定义注解实现通用的数据读取

1、正常情况是需要有一个方法提供data provider,然后测试方法调用名字,而excel的路径和sheet表名写在调用的地方,

2、通过注解实现excel文件配置读取,用户无需关心读取过程,只需设置配置路径

3、下面是测试用例


public class Demo extends ExcelDataHeleper {

     //excel文件读取

    @Test(dataProvider="excel")

    @DataFile(path ="excel/addStudentTemplate.xls",sheet ="Sheet0")

    public void testmethod1(Map param){

              System.out.println(param.get("id")+"    "+param.get("phone"));

    }

   //csv文件读取

    @Test(dataProvider="csv")

    @DataFile(path ="csv/a.csv")

    public void testmethodCsv(Map param){
              System.out.println(param.get("id")+"    "+param.get("phone"));

    }

    //yaml文件读取
    @Test(dataProvider="yaml")

    @DataFile(path ="yaml/a.yaml",key="user")

    public void testmethodYaml(Map param){
              System.out.println(param.get("id")+"    "+param.get("phone"));

    }

}

dataProvider:标注读取的是excel文件

DataFile中的path:excel的相对路径,在res下,sheet:表格的sheet名

param:为hashMap,通过表格中的键读取值

DataFile类如下

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DataFile {
    public String path();  //注解元素 为  id
    public String sheet() default "no description"; //设置默认值,
}

下面介绍继承的基类:ExcelDataHeleper

import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.testng.annotations.DataProvider;
import java.io.*;
import java.lang.reflect.Method;
import java.util.*;
public class ExcelDataHeleper {

    @DataProvider(name = "excel")
    public Iterator dataMethod(Method m) {
        System.out.println(m.getName());
        DataFile d = m.getAnnotation(DataFile.class);
        System.out.println(d.path() + "   " + d.sheet());
        List item = new ArrayList();
        List> list = read(d.path(), d.sheet());
        if (list != null || list.size() > 0) {
            int size = list.get(0).size();
            for (int i = 1; i < list.size(); i++) {
                Map map = new HashMap<>();
                for (int j = 0; j < size; j++) {
                    map.put(list.get(0).get(j), list.get(i).get(j));
                }
                item.add(map);
            }
        }
        List users = new ArrayList();
        for (Object u : item) {
            //做一个形式转换
            users.add(new Object[]{u});
        }
        return users.iterator();
    }
   //yaml文件
    @DataProvider(name = "yaml")
    public Iterator dataMethodYaml(Method m) {
        System.out.println(m.getName());
        DataFile d = m.getAnnotation(DataFile.class);
        logger.info(d.path() + "   " + d.key());
        List item = new ArrayList();
        InputStream in = ClassLoader.getSystemResourceAsStream(d.path());
        Yaml yaml = new Yaml();
        Map map = yaml.loadAs(in, Map.class);
        List > appid = (List>) map.get(d.key());
//        System.out.println(appid.get(1).get("username"));
        List users = new ArrayList();
        for (Object u : appid) {
            //做一个形式转换
            users.add(new Object[]{u});
        }
        return users.iterator();
    }

    //csv文件读取,还没写完
    @DataProvider(name = "csv")
    public Iterator dataMethod1(Method m) {
        DataFile d = m.getAnnotation(DataFile.class);
        File inFile = new File(System.getProperty("user.dir") + File.separator + "src/main/resources/" + d.path());
        try {
            BufferedReader reader = new BufferedReader(new FileReader(inFile));
            boolean sign = false;       //用来跳过第一行的名称
            List item = new ArrayList();
            List list = new ArrayList<>();
            String[] title = new String[0];
            while (reader.ready()) {
                String line = reader.readLine();
                String[] string = line.split(",");
                if (!sign) {
                    sign = true;
                    title = string;
                } else {
                    Map map = new HashMap<>();
                    if (string != null && string.length > 0 && title != null && title.length > 0) {
                        for (int j = 0; j < title.length; j++) {
                            map.put(specialUnicode(title[j]), string[j]);
                            //map.put(title[j], string[j]);
                        }
                        item.add(map);
                    }
                }
            }
            reader.close();
            List users = new ArrayList();
            for (Object u : item) {
                //做一个形式转换
                users.add(new Object[]{u});
            }
            return users.iterator();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return null;
    }

    public List> read(String fileName, String sheetName) {
        List> maps = new ArrayList<>();
        if (fileName == null || !fileName.matches("^.+\\.(?i)((xls)|(xlsx))$"))
            return maps;
        try {
            InputStream inputStream = new FileInputStream(System.getProperty("user.dir") + File.separator + "src/main/resources/" + fileName);
            System.out.println(inputStream);
            Workbook wb = WorkbookFactory.create(inputStream);
            maps = read(wb, sheetName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return maps;
    }

    private int totalRows = 0;// 总行数
    private int totalCells = 0;// 总列数

    private List> read(Workbook wb, String sheetName) {
        List> maps = new ArrayList<>();
        List> list = new ArrayList>();
        int delnumber = 0;// 第一页去除行数
        Sheet sheet = wb.getSheet(sheetName);
        this.totalRows = sheet.getPhysicalNumberOfRows() - delnumber; // 获取工作表中行数
        if (this.totalRows >= 1 && sheet.getRow(delnumber) != null) {
            this.totalCells = sheet.getRow(0)
                    .getPhysicalNumberOfCells(); // 得到当前行的所有单元格
            for (int j = 0; j < totalRows; j++) {
                List rowLst = new ArrayList();
                for (int f = 0; f < totalCells; f++) {
                    if (totalCells > 0) {
                        String value = getCell(sheet.getRow(j).getCell(f));
                        rowLst.add(value);
                    }
                }
                list.add(rowLst);
            }
        }
        return list;
    }
    /*
     * private String getRightStr(String sNum) { DecimalFormat decimalFormat =
     * new DecimalFormat("##.00"); String resultStr = decimalFormat.format(new
     * Double(sNum)); if (resultStr.matches("^[-+]?\\d+\\.[0]+$")) { resultStr =
     * resultStr.substring(0, sNum.indexOf(".")); } return resultStr; }
     */

    public String getCell(Cell cell) {
        String cellValue = null;
        HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
        cellValue = hSSFDataFormatter.formatCellValue(cell); // 使用EXCEL原来格式的方式取得值
        return cellValue;
    }

 /**
     * 去除 字符串收尾的 特殊的Unicode [ "\uFEFF" ]
     * csv 文件可能会带有该编码
     * @param str
     * @return
     */
    private static String specialUnicode(String str){
        if (str.startsWith("\uFEFF")){
            str = str.replace("\uFEFF", "");
        }else if (str.endsWith("\uFEFF")){
            str = str.replace("\uFEFF","");
        }
        return str;
    }
{

 
 

注:因为csv文件有时候会隐藏一些标识符号,如果不去除,会导致通过map的key获取不到对应的值,所以加入了specialUnicode方法

pom.xml添加依赖

 
  org.apache.poi
  poi
  3.17



  org.apache.poi
  poi-ooxml
  3.17

excel中内容:
Testng+DataProvider+自定义注解实现通用的数据读取_第1张图片
image.png

运行结果如下:
Testng+DataProvider+自定义注解实现通用的数据读取_第2张图片
image.png

有问题联系我,微信:fwrsmile

你可能感兴趣的:(Testng+DataProvider+自定义注解实现通用的数据读取)