• TestNG+Excel+(HTTP+JSON) 简单接口测试


    说明:

    1.使用Exce作为数据存放地;

    2.使用TestNG的Datarprovide 做数据供应;

    3.不足的地方没有指定明确的result_code , error_code , ERROR_MSG ,如果知道明确规定error_code就可以直接用error_code来作为测试结果;

    4.代码有许多需要改动的地方本次是第一版;

    5.可以将整个小项目打成jar包执行,将excle的文件放入C盘根目录即可(毕竟每个电脑都有C盘,这样就不受机器的限制了)

    6.关于本次用到的jar包有

    一,读取EXCLE的相关代码

      1 package main.java;
      2 
      3 import org.apache.poi.ss.usermodel.*;
      4 
      5 import java.io.File;
      6 import java.io.FileInputStream;
      7 import java.io.IOException;
      8 import java.util.ArrayList;
      9 import java.util.HashMap;
     10 import java.util.List;
     11 import java.util.Map;
     12 
     13 public class ExcelReader {
     14     private String filePath;
     15     private String sheetName;
     16     private Workbook workBook;
     17     private Sheet sheet;
     18     private List<String> columnHeaderList;
     19     private List<List<String>> listData;
     20     private List<Map<String, String>> mapData;
     21     private boolean flag;
     22     public Object[][] results;
     23 
     24     public ExcelReader(String filePath, String sheetName) {
     25         this.filePath = filePath;
     26         this.sheetName = sheetName;
     27         this.flag = false;
     28         this.load();
     29     }
     30 
     31     private void load() {
     32         FileInputStream inStream = null;
     33         try {
     34             inStream = new FileInputStream(new File(filePath));
     35             workBook = WorkbookFactory.create(inStream);
     36             sheet = workBook.getSheet(sheetName);
     37         } catch (Exception e) {
     38             e.printStackTrace();
     39         } finally {
     40             try {
     41                 if (inStream != null) {
     42                     inStream.close();
     43                 }
     44             } catch (IOException e) {
     45                 e.printStackTrace();
     46             }
     47         }
     48     }
     49 
     50     private String getCellValue(Cell cell) {
     51         String cellValue = "";
     52         DataFormatter formatter = new DataFormatter();
     53         if (cell != null) {
     54             switch (cell.getCellType()) {
     55                 case Cell.CELL_TYPE_NUMERIC:
     56                     if (DateUtil.isCellDateFormatted(cell)) {
     57                         cellValue = formatter.formatCellValue(cell);
     58                     } else {
     59                         double value = cell.getNumericCellValue();
     60                         int intValue = (int) value;
     61                         cellValue = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);
     62                     }
     63                     break;
     64                 case Cell.CELL_TYPE_STRING:
     65                     cellValue = cell.getStringCellValue();
     66                     break;
     67                 case Cell.CELL_TYPE_BOOLEAN:
     68                     cellValue = String.valueOf(cell.getBooleanCellValue());
     69                     break;
     70                 case Cell.CELL_TYPE_FORMULA:
     71                     cellValue = String.valueOf(cell.getCellFormula());
     72                     break;
     73                 case Cell.CELL_TYPE_BLANK:
     74                     cellValue = "";
     75                     break;
     76                 case Cell.CELL_TYPE_ERROR:
     77                     cellValue = "";
     78                     break;
     79                 default:
     80                     cellValue = cell.toString().trim();
     81                     break;
     82             }
     83         }
     84         return cellValue.trim();
     85     }
     86 
     87     private void getSheetData() {
     88 
     89         listData = new ArrayList<>();
     90         mapData = new ArrayList<>();
     91         columnHeaderList = new ArrayList<>();
     92         int numOfRows = sheet.getLastRowNum() + 1;
     93         for (int i = 0; i < numOfRows; i++) {
     94             Row row = sheet.getRow(i);
     95             Map<String, String> map = new HashMap<>();
     96             List<String> list = new ArrayList<>();
     97 
     98             if (row != null) {
     99                 for (int j = 0; j < row.getLastCellNum(); j++) {
    100                     Cell cell = row.getCell(j);
    101                     if (i == 0) {
    102                         columnHeaderList.add(getCellValue(cell));
    103                     } else {
    104 
    105                         map.put(columnHeaderList.get(j), this.getCellValue(cell));
    106 
    107                     }
    108                     list.add(this.getCellValue(cell));
    109                 }
    110             }
    111             if (i > 0) {
    112                 mapData.add(map);
    113             }
    114             listData.add(list);
    115 
    116 
    117         }
    118 
    119         flag = true;
    120 
    121         for (int i = 0; i < listData.size(); i++) {
    122             for (int j = 0; j < listData.get(i).size(); j++) {
    123                 System.out.println(listData.get(i).get(j).toString());
    124             }
    125         }
    126 
    127     }
    128 
    129     public String getCellData(int row, int col) {
    130         if (row <= 0 || col <= 0) {
    131             return null;
    132         }
    133         if (!flag) {
    134             this.getSheetData();
    135         }
    136         if (listData.size() >= row && listData.get(row - 1).size() >= col) {
    137             return listData.get(row - 1).get(col - 1);
    138         } else {
    139             return null;
    140         }
    141     }
    142 
    143     public String getCellData(int row, String headerName) {
    144         if (row <= 0) {
    145             return null;
    146         }
    147         if (!flag) {
    148             this.getSheetData();
    149         }
    150         if (mapData.size() >= row && mapData.get(row - 1).containsKey(headerName)) {
    151             return mapData.get(row - 1).get(headerName);
    152         } else {
    153             return null;
    154         }
    155     }
    156 
    157 
    158     public Object[][] getSheetData2() {
    159 
    160         List<Object[]> result = new ArrayList<>();
    161         listData = new ArrayList<>();
    162         mapData = new ArrayList<>();
    163         columnHeaderList = new ArrayList<>();
    164 
    165         int numOfRows = sheet.getLastRowNum() + 1;
    166         System.out.println("总共有 " + numOfRows + "行 !");
    167         for (int i = 0; i < numOfRows; i++) {
    168             Row row = sheet.getRow(i);
    169             Map<String, String> map = new HashMap<>();
    170             List<String> list = new ArrayList<>();
    171             Object[] o1 = new Object[row.getLastCellNum()];
    172 
    173             if (row != null) {
    174                 for (int j = 0; j < row.getLastCellNum(); j++) {
    175                     //   System.out.println("第 "+i+" 行--- row.getLastCellNum()===="+row.getLastCellNum());
    176                     Cell cell = row.getCell(j);
    177                     if (i == 0) {
    178                         o1[j] = this.getCellValue(cell);
    179                         //       System.out.println(j+"------this.getCellValue(cell)="+this.getCellValue(cell));
    180                         columnHeaderList.add(getCellValue(cell));
    181                     } else {
    182                         o1[j] = this.getCellValue(cell);
    183                         // System.out.println(j+"------this.getCellValue(cell)="+this.getCellValue(cell));
    184                         map.put(columnHeaderList.get(j), this.getCellValue(cell));
    185 
    186                     }
    187                     list.add(this.getCellValue(cell));
    188                 }
    189             }
    190             if (i > 0) {
    191                 mapData.add(map);
    192             }
    193             result.add(o1);
    194             listData.add(list);
    195         }
    196         // 测试数据excel数据用 ;
    197       /*    for (int i = 0; i < result.size(); i++) {
    198             for (int j = 0; j < result.get(i).length; j++) {
    199                 System.out.print(result.get(i)[j]+" | ");
    200             }
    201             System.out.println();
    202         }*/
    203         results = new Object[result.size()][];
    204 
    205         for (int i = 0; i < result.size(); i++) {
    206             results[i] = result.get(i);
    207         }
    208         flag = true;
    209 
    210         System.out.println("results.length==" + results.length);
    211         return results;
    212     }
    213 
    214     public static void main(String[] args) {
    215  /*       Object[][] obj1;
    216         ExcelReader eh = new ExcelReader("C:\TEST.xlsx", "Sheet1");
    217         Object[][] sheetData2 = eh.getSheetData2();
    218         System.out.println(sheetData2.length + "------------");
    219         for (int i = 1; i < sheetData2.length; i++) {
    220             for (int j = 0; j < sheetData2[i].length; j++) {
    221                 System.out.print(sheetData2[i][j] + " | ");
    222             }
    223             System.out.println();
    224         }*/
    225 
    226 
    227     }
    228 }
    View Code

    二,ExcelUtil工具类

      1 package main.java;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileOutputStream;
      6 import java.util.ArrayList;
      7 import java.util.List;
      8 
      9 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
     10 import org.apache.poi.ss.usermodel.Row;
     11 import org.apache.poi.ss.usermodel.Sheet;
     12 import org.apache.poi.ss.usermodel.Workbook;
     13 import org.apache.poi.xssf.usermodel.XSSFCell;
     14 import org.apache.poi.xssf.usermodel.XSSFRow;
     15 import org.apache.poi.xssf.usermodel.XSSFSheet;
     16 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
     17 
     18 
     19 public class ExcleUtil {
     20     private static XSSFSheet ExcelWSheet;
     21     private static XSSFWorkbook ExcelWBook;
     22     private static XSSFCell Cell;
     23     private static XSSFRow Row;
     24     private static String ExcelFilePath="C:\TEST.xlsx";
     25 
     26     // 设定要设置的Excel的文件路径和Excel 中Sheet名;
     27     // 在读/写Excel 的时候先要调用此方法
     28     public static void setExcleFile(String FilePath, String sheetName) throws Exception {
     29         FileInputStream ExcleFile;
     30         try {
     31             // 实例化Excle文件的FileInputStream 对象;
     32             ExcleFile = new FileInputStream(FilePath);
     33             // 实例化Excle文件的XSSFWorkbook 对象;
     34             ExcelWBook = new XSSFWorkbook(ExcleFile);
     35             /*
     36              * 实例化XSSFSheet 对象,指定ExcelFile中的sheet名称,用于后续对sheet中行和列的操作;
     37              * 
     38              */
     39             ExcelWSheet = ExcelWBook.getSheet(sheetName);
     40 
     41         } catch (Exception e) {
     42             e.getStackTrace();
     43         }
     44 
     45     }
     46     /*
     47      * 读取excle文件指定单元格的函数 ;
     48      * 
     49      */
     50 
     51     public static String getCell(int row, int col) throws Exception {
     52 
     53         try {
     54             // 通过函数参数指定单元格的行号和列,获取指定单元格的对象;
     55             Cell = ExcelWSheet.getRow(row).getCell(col);
     56             /*
     57              * 1.如果单元格的类型为字符串类型,使用getStringCellValue();来获取单元格的内容;
     58              * 2.如果单元格的类型为数字类型,使用getNumberricCellValue();来获取单元格的内容;
     59              * 注意:getNumberricCellValue();返回的值为double类型,转为为字符串类型,必须在
     60              * getNumberricCellValue();前面加上(" ")双引号,用于强制转换为String类型,不加双引号
     61              * 则会抛错;double类型无法转换为String类型的异常;
     62              * 
     63              */
     64             String CellData = Cell.getCellType() == XSSFCell.CELL_TYPE_STRING ? Cell.getStringCellValue() + ""
     65                     : String.valueOf(Math.round(Cell.getNumericCellValue()));
     66             return CellData;
     67         } catch (Exception e) {
     68             e.getStackTrace();
     69             return "";
     70         }
     71 
     72     }
     73     /*
     74      * 在Excle中执行单元格写入数据;
     75      * 
     76      * 
     77      */
     78 
     79     public static void setCellData(int rownum, int colnum, String Result) throws Exception {
     80 
     81         try {
     82             // 获取excle文件的中行对象;
     83             Row = ExcelWSheet.getRow(rownum);
     84             // 如果单元格为空则返回null;
     85             Cell = Row.getCell(colnum, Row.RETURN_BLANK_AS_NULL);
     86             if (Cell == null) {
     87                 // 当单元格为空是则创建单元格
     88                 // 如果单元格为空无法调用单元格对象的setCellValue方法设定单元格的值 ;
     89                 Cell = Row.createCell(colnum);
     90                 // 创建单元格和后可以通过调用单元格对象的setCellValue方法设置单元格的值了;
     91                 Cell.setCellValue(Result);
     92             } else {
     93                 // 单元格中有内容,则可以直接调用单元格对象的 setCellValue 方法来设置单元格的值;
     94                 Cell.setCellValue(Result);
     95             }
     96             FileOutputStream fileout = new FileOutputStream(ExcelFilePath);
     97             // 将内容写到Excel文件中 ;
     98             ExcelWBook.write(fileout);
     99             // j调用flush方法强制刷新写入文件;
    100             fileout.flush();
    101             fileout.close();
    102             System.out.println("-----写入成功!------");
    103         } catch (Exception e) {
    104             System.out.println(e.getMessage() + e.getStackTrace());
    105             throw (e);
    106         }
    107 
    108     }
    109 
    110     public static void TangsetCellData(int RowNum, int ColNum, String Result) {
    111         try {
    112             // 获取行对象
    113             Row = ExcelWSheet.getRow(RowNum);
    114             // 如果单元格为空,则返回null
    115             Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
    116             if (Cell == null) {
    117                 // 当单元格对象是Null时,则创建单元格
    118                 // 如果单元格为空,无法直接调用单元格的setCellValue方法设定单元格的值
    119                 Cell = Row.createCell(RowNum);
    120                 // 调用setCellValue方法设定单元格的值
    121                 Cell.setCellValue(Result);
    122             } else {
    123                 // 单元格中有内容,则可以直接调用seCellValue方法设定单元格的值
    124                 Cell.setCellValue(Result);
    125             }
    126             // 实例化写入Excel文件的文件输出流对象
    127             FileOutputStream fileOut = new FileOutputStream(ExcelFilePath);
    128             // 将内容写入Excel中
    129             ExcelWBook.write(fileOut);
    130             fileOut.flush();
    131             fileOut.close();
    132         } catch (Exception e) {
    133             // TODO: handle exception
    134             e.printStackTrace();
    135         }
    136     }
    137 
    138     // 从excel 文件中获取测试数据的静态方法;
    139     public static Object[][] getTestData(String excelFilePath, String sheetName) throws Exception {
    140         // 根据参数传入的数据文件路径和文件名称,组合出Excel 数据文件的绝对路径
    141         // 声明一个文件;
    142         File file = new File(excelFilePath);
    143         // 创建FileInputStream 来读取Excel文件内容;
    144         FileInputStream inputStream = new FileInputStream(file);
    145         // 声明Workbook 对象;
    146         Workbook workbook = null;
    147         // 获取文件名参数的扩展名,判断是“.xlsx” 还是 “.xls” ;
    148         String fileExtensionName = excelFilePath.substring(excelFilePath.indexOf('.'));
    149         if (fileExtensionName.equals(".xlsx")) {
    150             workbook = new XSSFWorkbook(inputStream);
    151 
    152         } else if (fileExtensionName.equals(".xls")) {
    153             workbook = new HSSFWorkbook(inputStream);
    154 
    155         }
    156         Sheet sheet = workbook.getSheet(sheetName);
    157         // 获取Excel 数据文件Sheet1 中数据的行数,getLastRowNum 方法获取数据的最后一行的行号,
    158         // getFistRowNum 获取第一行 最后一行减去第一行就是总行数了
    159         // 注意excle 的行和列都是从0开始的;
    160         int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
    161         // 创建名为records 的List对象来存储从Excel文件中读取的数据;
    162         List<Object[]> records = new ArrayList<Object[]>();
    163         // 使用for循环遍历Excel 数据文件的所有数据(除了第一行,第一行为标题行),所以i从1开始而不是从0开始;
    164 
    165         for (int i = 1; i < rowCount + 1; i++) {
    166             // 使用getRow来获取行对象;
    167             Row row = sheet.getRow(i);
    168             /*
    169              * 声明一个数据,用来存储Excel数据文件每行中的测试用例和数据,数据的大小用getLastCellNum-2
    170              * 来进行动态声明,实现测试数据个数和数组大小一致,
    171              * 因为Excel数据文件中的测试数据行的最后一个单元格是测试执行结果,倒数第二个单元格为此测试数据行是否运行的状态位,
    172              * 所以最后俩列的单元格数据并
    173              * 不需要传入测试方法中,所以是用getLastCellNum-2的方式去掉每行中的最后俩个单元格数据,计算出需要存储的测试数据个数,
    174              * 并作为测试数据数组的初始化大小
    175              * 
    176              */
    177             String fields[] = new String[row.getLastCellNum() - 2];
    178 
    179             /*
    180              * 判断数据行是否要参与测试的执行,Excel 文件的倒数第二列为数据行的状态位, 标记为“y”
    181              * 表示此数据行要被测试脚本执行,标记为非“y”的数据行均被认为不会参数测试脚本执行,会被跳过;
    182              */
    183 
    184             if (row.getCell(row.getLastCellNum() - 2).getStringCellValue().equals("y")) {
    185                 for (int j = 0; j < row.getLastCellNum() - 2; j++) {
    186                     /*
    187                      * 判断Excel 单元格的内容是数字还是字符, 字符格式调用:
    188                      * row.getCell(j).getStringCellValue();
    189                      * 数字格式调用:row.getCell(j).getNumericCellValue();
    190                      */
    191                     fields[j] = (String) (row.getCell(j).getCellType() == XSSFCell.CELL_TYPE_STRING
    192                             ? row.getCell(j).getStringCellValue() : "" + row.getCell(j).getNumericCellValue());
    193 
    194                 }
    195                 // fields 存储到数组当中;
    196                 records.add(fields);
    197 
    198             }
    199         }
    200 
    201         /*
    202          * 定义函数的返回值,即Object[] [] 将存储测试数据的list 转换为一个Object 的二维数组;
    203          */
    204         Object[][] results = new Object[records.size()][];
    205         for (int i = 0; i < records.size(); i++) {
    206             results[i] = records.get(i);
    207         }
    208 
    209         return results;
    210 
    211     }
    212 
    213     public static int getLastColumnNum() {
    214 
    215         return ExcelWSheet.getRow(0).getLastCellNum() - 1;
    216     }
    217 
    218 
    219 
    220 
    221 }
    View Code

    三,接口get和post方法

      1 package main.java;
      2 
      3 import net.sf.json.JSON;
      4 import net.sf.json.JSONObject;
      5 
      6 import java.io.BufferedReader;
      7 import java.io.IOException;
      8 import java.io.InputStreamReader;
      9 import java.io.PrintWriter;
     10 import java.net.URL;
     11 import java.net.URLConnection;
     12 import java.util.List;
     13 import java.util.Map;
     14 
     15 /**
     16  * Created by ty on 2017/8/17.
     17  */
     18 public class HttpInterfaceTest {
     19 
     20 
     21     public String sendGet(String url, String param) {
     22         String result = "";
     23         BufferedReader in = null;
     24         try {
     25             String urlName = url + "?" + param;
     26             System.out.println("Get请求接口:" + urlName);
     27             URL realUrl = new URL(urlName);
     28             // 打开和URL之间的连接
     29             URLConnection conn = realUrl.openConnection();
     30             // 设置通用的请求属性
     31             conn.setRequestProperty("accept", "*/*");
     32             conn.setRequestProperty("connection", "Keep-Alive");
     33             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
     34             // 建立实际的连接
     35             conn.connect();
     36             // 获取所有响应头字段
     37             Map<String, List<String>> map = conn.getHeaderFields();
     38             // 遍历所有的响应头字段
     39             for (String key : map.keySet()) {
     40                 System.out.println(key + "--->" + map.get(key));
     41             }
     42             // 定义BufferedReader输入流来读取URL的响应
     43             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
     44             String line;
     45             while ((line = in.readLine()) != null) {
     46                 result += "
    " + line;
     47             }
     48         } catch (Exception e) {
     49             System.out.println("发送GET请求出现异常!" + e);
     50             e.printStackTrace();
     51         }
     52         // 使用finally块来关闭输入流
     53         finally {
     54             try {
     55                 if (in != null) {
     56                     in.close();
     57                 }
     58             } catch (IOException ex) {
     59                 ex.printStackTrace();
     60             }
     61         }
     62         return result;
     63     }
     64 
     65     /**
     66      * 向指定URL发送POST方法的请求
     67      *
     68      * @param url   发送请求的URL
     69      * @param param 请求参数,请求参数应该是name1=value1&name2=value2的形式或者是json。
     70      * @return URL所代表远程资源的响应
     71      */
     72     public String sendPost(String url, String param) {
     73         PrintWriter out = null;
     74         BufferedReader in = null;
     75         String result = "";
     76         try {
     77             URL realUrl = new URL(url);
     78             // 打开和URL之间的连接
     79             URLConnection conn = realUrl.openConnection();
     80             // 设置通用的请求属性
     81             conn.setRequestProperty("accept", "*/*");
     82             conn.setRequestProperty("connection", "Keep-Alive");
     83             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
     84             conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
     85             // 发送POST请求必须设置如下两行
     86             conn.setDoOutput(true);
     87             conn.setDoInput(true);
     88 
     89             // 获取URLConnection对象对应的输出流
     90             out = new PrintWriter(conn.getOutputStream());
     91             // 发送请求参数
     92             out.print(param);
     93             // flush输出流的缓冲
     94             out.flush();
     95             // 定义BufferedReader输入流来读取URL的响应
     96             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
     97             String line;
     98             while ((line = in.readLine()) != null) {
     99                 result += "
    " + line;
    100             }
    101         } catch (Exception e) {
    102             System.out.println("发送POST请求出现异常!" + e);
    103             e.printStackTrace();
    104         }
    105         // 使用finally块来关闭输出流、输入流
    106         finally {
    107             try {
    108                 if (out != null) {
    109                     out.close();
    110                 }
    111                 if (in != null) {
    112                     in.close();
    113                 }
    114             } catch (IOException ex) {
    115                 ex.printStackTrace();
    116             }
    117         }
    118         return result;
    119     }
    120 
    121 
    122     public static void main(String[] args) {
    123 
    124         HttpInterfaceTest httpInterfaceTest = new HttpInterfaceTest();
    125 
    126         // 调用天气预报接口请求参数方式一
    127         String postUrl = "http://op.juhe.cn/onebox/weather/query";
    128         String postParamsOne = "&cityname=上海市" + "&key=1234567890";
    129         // 调用天气预报接口请求参数方式二
    130         String postParamsTwo = "{'cityname':'上海市'," + "'key':'1234567890'}";
    131         JSONObject jsonPostParamsTwo = JSONObject.fromObject(postParamsTwo);
    132         System.out.println("----------------");
    133         // 发送POST请求
    134         String postResultOne = httpInterfaceTest.sendPost(postUrl, postParamsOne);
    135         System.out.println("POST请求参数一:" + postParamsOne);
    136         System.out.println("POST请求响应结果:" + postResultOne);
    137         // 发送POST请求
    138         String postResultTwo = httpInterfaceTest.sendPost(postUrl, jsonPostParamsTwo.toString());
    139         System.out.println("POST请求参数二:" + jsonPostParamsTwo);
    140         System.out.println("POST请求响应结果:" + postResultTwo);
    141 
    142         JSONObject jsonObject = JSONObject.fromObject(postResultTwo);
    143         Object resultcode = jsonObject.get("resultcode");
    144         Object reason = jsonObject.get("reason");
    145         Object error_code = jsonObject.get("error_code");
    146         System.out.println("resultcode==" + resultcode+
    147                 "|  reason="+reason+"    | error_code= "+error_code);
    148     }
    149 }
    View Code

    四,测试类

     1 package main.test;
     2 
     3 import main.java.ExcelReader;
     4 import main.java.ExcleUtil;
     5 import main.java.HttpInterfaceTest;
     6 import net.sf.json.JSONException;
     7 import net.sf.json.JSONObject;
     8 import org.testng.annotations.BeforeTest;
     9 import org.testng.annotations.DataProvider;
    10 import org.testng.annotations.Test;
    11 
    12 import static org.testng.Assert.*;
    13 
    14 /**
    15  * Created by linbo.yang on 2017/9/5.
    16  */
    17 public class TestHttpInterfaceTest {
    18    public static HttpInterfaceTest ht ;
    19     ExcelReader ex ;
    20     static ExcleUtil excleUtil;
    21     @BeforeTest
    22     public void init(){
    23         String ExcelFilePath="C:\TEST.xlsx";
    24         String sheetName="Sheet1";
    25          ht=new HttpInterfaceTest();
    26         ex = new ExcelReader(ExcelFilePath, sheetName);
    27         try {
    28             excleUtil.setExcleFile( ExcelFilePath,sheetName);
    29         } catch (Exception e) {
    30             e.printStackTrace();
    31         }
    32     }
    33 
    34     @Test(dataProvider = "dp")
    35     public void testSendPost(String rowNum,String Url,String paras) throws Exception {
    36         System.out.println("rowNum="+rowNum+";  URL="+Url+" ;   paras="+paras);
    37         Integer it = new Integer(rowNum);
    38          int row=it.intValue();
    39         if (paras.contains("&")){
    40             String s1 =  ht.sendPost(Url,paras );
    41             excleUtil.setCellData(row,3,s1);
    42             System.out.println(s1);
    43         }else {
    44             try {
    45                 JSONObject jsonObject = JSONObject.fromObject(paras);
    46                 String s  =  ht.sendPost(Url, jsonObject.toString());
    47                 excleUtil.setCellData(row,3,s);
    48                 System.out.println(s);
    49             }catch (JSONException jsonException){
    50 
    51                 System.out.println("标题行不能进行转换!");
    52             }
    53 
    54         }
    55 
    56 
    57     }
    58     @DataProvider
    59     public Object[][] dp(){
    60      Object[][] sheetData2 = ex.getSheetData2();
    61         /*   System.out.println(sheetData2.length + "------------");
    62         for (int i = 1; i < sheetData2.length; i++) {
    63             for (int j = 0; j < sheetData2[i].length; j++) {
    64                 System.out.print(sheetData2[i][j] + " | ");
    65             }
    66             System.out.println();
    67         }*/
    68 
    69 
    70         return  sheetData2 ;
    71 
    72     }
    73 
    74 }
    View Code

    五,日期工具类可以将测试的时间写入到excle中去

      1 package main.java;
      2 
      3 import java.util.*;
      4 public class DateUtil {
      5         public static String format="yyyy/MM/dd HH:mm:ss";
      6     public static Date date = new Date();
      7     /*
      8      * 格式化输出日期 ;
      9      * 
     10      * @return 一个字符型日期;
     11      */
     12     public static String format(Date date ,String format) {
     13         String result = "";
     14         try {
     15             if (date != null) {
     16                 java.text.DateFormat df = new java.text.SimpleDateFormat(format);
     17                 result = df.format(date);
     18 
     19             }
     20         } catch (Exception e) {
     21             e.printStackTrace();
     22         }
     23         return result;
     24     }
     25     public static String format() {
     26         String result = "";
     27         try {
     28             if (date != null) {
     29                 java.text.DateFormat df = new java.text.SimpleDateFormat(format);
     30                 result = df.format(date);
     31 
     32             }
     33         } catch (Exception e) {
     34             e.printStackTrace();
     35         }
     36         return result;
     37     }
     38 
     39 
     40     public String getYear() {
     41         java.util.Calendar c= java.util.Calendar.getInstance();
     42         c.setTime(date);
     43         return String.valueOf(c.get(java.util.Calendar.YEAR)) ;
     44     }
     45 
     46     //返回年份 ;
     47     public  static String getYear(java.util.Date date){
     48         java.util.Calendar c= java.util.Calendar.getInstance();
     49         c.setTime(date);
     50         return String.valueOf(c.get(java.util.Calendar.YEAR)) ;
     51     }
     52 //返回月份 ;
     53 public static String getMonth(){
     54     java.util.Calendar calendar =java.util.Calendar.getInstance();
     55     calendar.setTime(date);
     56     return     String.valueOf(calendar.get(java.util.Calendar.MONTH)+1);
     57 }
     58     public static String getMonth(java.util.Date date){
     59         java.util.Calendar calendar =java.util.Calendar.getInstance();
     60         calendar.setTime(date);
     61     return     String.valueOf(calendar.get(java.util.Calendar.MONTH)+1);
     62     }
     63 //返回月份中的第几天;
     64 
     65     public  static String getDay(){
     66         java.util.Calendar calendar =java.util.Calendar.getInstance();
     67         calendar.setTime(date);
     68         return String.valueOf(calendar.get(java.util.Calendar.DAY_OF_MONTH));
     69     }
     70     public  static String getDay(java.util.Date date){
     71     java.util.Calendar calendar =java.util.Calendar.getInstance();
     72     calendar.setTime(date);
     73     return String.valueOf(calendar.get(java.util.Calendar.DAY_OF_MONTH));
     74     }
     75     //返回小时;
     76     public  static String getHour(){
     77         Calendar calendar=Calendar.getInstance();
     78         calendar.setTime(date);
     79         return String.valueOf(calendar.get(Calendar.HOUR));
     80     }
     81     public  static String getHour(Date date){
     82     Calendar calendar=Calendar.getInstance();
     83     calendar.setTime(date);
     84     return String.valueOf(calendar.get(Calendar.HOUR));
     85     }
     86 //返回分钟 ;
     87 public static String getMinute( ){
     88     Calendar calendar = Calendar.getInstance();
     89     calendar.setTime(date);
     90     return String.valueOf(calendar.get(Calendar.MINUTE));
     91 }
     92     public static String getMinute(Date date ){
     93         Calendar calendar = Calendar.getInstance();
     94         calendar.setTime(date);
     95         return String.valueOf(calendar.get(Calendar.MINUTE));
     96     }
     97 //返回秒
     98 public static String getSecond( ){
     99     Calendar calendar = Calendar.getInstance();
    100     calendar.setTime(date);
    101     return String.valueOf(calendar.get(Calendar.SECOND));
    102 }
    103     public static String getSecond(Date date ){
    104         Calendar calendar = Calendar.getInstance();
    105         calendar.setTime(date);
    106         return String.valueOf(calendar.get(Calendar.SECOND));
    107     }
    108 }
    View Code


    六,执行结果

     

  • 相关阅读:
    Python之路:堡垒机实例
    Django入门
    阿里云centos安装svn和submin
    发邮件功能
    [Coci2015]Divljak
    [2018多省省队联测]劈配
    [AHOI2009]最小割
    [HAOI2017]新型城市化
    [SDOI2014]LIS
    Loj #2256. 「SNOI2017」英雄联盟
  • 原文地址:https://www.cnblogs.com/linbo3168/p/7479615.html
Copyright © 2020-2023  润新知