java+testng利用json格式的txt做数据源的数据驱动示例
在接口自动化中,利用testng的@DataProvider可以数据驱动,数据源文件可以是EXCEL,XML,YAML,甚至可以是TXT文本。在这以json格式的txt为例:
TestData.txt:
{ "name":"test1",
"request":{
"url":"/v1/test",
"method":"post",
"body":
{
"platformCode": "10001",
"productCode": "10002",
"userId": "123456"
}
}
};
{
"name":"test2",
"request":{
"url":"/v2/test",
"method":"post",
"body":
{
"platformCode": "10003",
"productCode": "10004",
"userId": "211234"
}
}
}
读取文件:
/** * 1.从文件中读取json格式的用例 * 2.因读取的信息为多个testcase,需拆分成多个case * 3.执行testcase */ public static String readTxt(String filePath){ StringBuffer sb = new StringBuffer(); try { FileReader reader=new FileReader(new File(filePath)); char[] byt=new char[1024]; int len = 0; while( (len = reader.read(byt)) != -1){ sb.append(new String(byt,0,len)); } } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } return sb.toString(); } /** * 根据字符C,拆分字符串 */ public static String[] parseStr(String str,String c){ return str.split(c); }
利用jackson解析json,然后把解析出来的信息转换成Object[][]类型的数据,并放到数据源中
@DataProvider(name="testData") public Object[][] getData(){ String[] data = parseStr(readTxt("localpath\\test-data\\AuditTest.txt"),";"); Object[][] testData = new Object[data.length][]; for(int i=0;i<data.length;i++){ ObjectMapper mapper=new ObjectMapper(); try { Map map = mapper.readValue(data[i], Map.class); testData[i]=new Object[]{(Map)map.get("request")}; } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return testData; }
用测试case测试一下
@Test(dataProvider="testData") public void test(Map param){ ObjectMapper mapper=new ObjectMapper(); String result = null; try { //因接口传参是json格式,把map转成json result = OkHttpUtil.postJson(Constance.test_host+param.get("url").toString(),mapper.writeValueAsString(param.get("body"))); //可添加断言 } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }