在接口自動化中,利用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(); } }