接口测试工具

本期讲述Excel+httpclient+testNG组成这个简单的接口测试工具,与网上其他同样的架构相比,此处优化了逻辑,一条用例支持多个接口相互传参。

整体思路是java脚本读取Excel中测试用例接口信息,通过testNG的DataProvidor数据提供商注入到@Test标记的测试用例,最后通过@Test标记的方法发起Http请求并做返回值处理。

下面直接进入主题。

  1. 读取Excel并存到双层Hash即HashMap<String, String>[][] testdata中。
    //循环行数 for (int i = 1; i < rowNum; i++) { //循环列数,依次将 <列名:value(第i行)>放入HashMap的二维数组 for (int j = 0; j < colNum; j++) { try { String cellValue = sheet.getRow(i).getCell(j).toString(); testdata[i - 1][0].put(columnName[j], cellValue); } catch (Exception e) { e.printStackTrace(); } } }

  2. DataProvider数据提供商对Excel中读取的数据二次处理,转换为包含多接口的测试用例一维矩阵。
    `Object[][] interfaces = ExcelReader.getExcelData("testcase.xlsx", "word");
    HashMap<String, String>[][] testdata = (HashMap<String, String>[][]) interfaces;
    assert interfaces != null;
    HashMap<Integer, HashMap> testCasesMap = new HashMap<>();
    //数据类型转换为 InterfaceVo
    for (int i = 0; i < interfaces.length; i++) {
    HashMap<String, String> map1 = testdata[i][0];
    InterfaceVo vo = initInterface(map1);
    HashMap map = new HashMap();
    map.put(vo.getUriNo(), vo);

         if (testCasesMap.get(vo.getTestNo()) == null) {
             testCasesMap.put(vo.getTestNo(), map);
         } else {
             testCasesMap.get(vo.getTestNo()).putAll(map);
         }
     }
    
     TestCaseVo[][] testCases = new TestCaseVo[testCasesMap.size()][1];
     for (int i = 0; i < testCases.length; i++) {
         testCases[0][i] = new TestCaseVo();
     }
    
     for (int i = 0; i < testCasesMap.size(); i++) {
         HashMap k = testCasesMap.get(i + 1);
         for (int j = 0; j < k.size(); j++) {
             HashMap map = testCasesMap.get(i + 1);
             InterfaceVo vo = (InterfaceVo) map.get(j + 1);
             testCases[i][0].addInterface(vo);
         }
     }`
    
  3. 单元测试方法执行用例,发起请求。
    @Test(dataProvider = "db") public void testMethod(TestCaseVo testCaseVo) { System.out.println("测试用例第" + testCaseVo.getTestNo() + "条"); HashMap<Object, Object> extraction = new HashMap<Object, Object>(16); List<InterfaceVo> interfaceVos = testCaseVo.getInterfaces(); InterfaceVo vo; JSONObject response; for (InterfaceVo interfaceVo : interfaceVos) { System.out.println("测试用例第" + testCaseVo.getTestNo() + "条;" + "接口第" + interfaceVo.getUriNo() + "个"); vo = interfaceVo; //数据清洗 replace(extraction, vo); response = new SysReader(vo).doRequest(); //返回值校验 check(response, vo); //返回值提取 extract(extraction, response, vo); } }
    ----------------------------------------------人工分割--------------------------------------

    基于上述代码可以小规模组织基于Excel的数据驱动单接口测试,不甚完善,沟通指正。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容