接口测试框架+数据驱动
前置知识
接口测试框架
采用HTTPOk + testNg 搭建而成,其中HttpOk 进行 http类型接口收发包,testNg 进行用例管理
背景
本文讲解项目中涉及到的数据驱动
项目中常用的数据驱动为@DataProvider 注解进行 经常将用例所需不同的场景参数以二维数组格式给出,
如:
@DataProvider(name = "paramsData")
public Object[][] paramsData() {
return new Object[][]{
{"创建行中实时路线分享", "1", createShareNaviData(locInfo, linkInfo, naviId, naviType, startPoint, endPoint, viaPoint, beforeShareId), "2"},
{"创建主图位置分享", "100", createShareDurtion(6000), "3"},
{"创建直播路线分享", "102", createShareLiveData("a38af2efe4940f2b33d321a8b123c916"), "4"},
{"创建直播路线分享", "101", createShareLiveData("a8c084090f26a38295e4a89e259000a6"), "4"},
{"创建行中实时路线分享", "4", createShareNaviData(locInfo, linkInfo, naviId, naviType, startPoint, endPoint, viaPoint, beforeShareId), "2"},
};
}
由于该版本需要对路线直播模块进行性能验证,如直播间需要加入人员500人
则需要引入客户给出的测试数据
脚本梳理/实现思路
- 框架需要给出与excel文件对应的模板类
- 需要将excel文件中的行数据转化为json串,将所有数据以json数组(JSONFAST实现)
- 将第二部解析的json数组转化为二维数组
脚本实现
- 构造excelPojo类,私有参数与excel文件列一一对应
public class ExcelPojo {
//excel列字段
private String uid;
private String name;
private String pwd;
@Override
public String toString() {
return "Pojo{" +
"uid='" + uid + '\'' +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
public String getUid() { return uid; }
public void setUid(String uid) { this.uid = uid; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getPwd() { return pwd; }
public void setPwd(String pwd) { this.pwd = pwd; }
}
- excel文件数据转化为JSONArray
public static String excel2Json(String name) {
Sheet sheet;
Workbook book;
Cell cell1, cell2;
JSONArray array = new JSONArray();
try {
book = Workbook.getWorkbook(new File(name));
sheet = book.getSheet(0);
for (int i = 1; i < sheet.getRows(); i++) {
cell1 = sheet.getCell(0, i);
cell2 = sheet.getCell(1, i);
if ("".equals(cell1.getContents())) {
break;
}
JSONObject object = new JSONObject();
object.put("name", cell1.getContents());
object.put("pwd", cell2.getContents());
array.add(object);
}
//System.out.println(array.toString());
System.out.println(array.size());
book.close();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (BiffException e) {
throw new RuntimeException(e);
}
return array.toString();
}
- DataProvider注解中将JSONArray 数据转化为二位数组,以适配脚本
@DataProvider(name = "dataParams",parallel=true)
public Object[][] dataParams() {
JSONArray ary = JSON.parseArray(excel2Json("case/perception/case/testData.xls"));//批量加入人员文件路径
Object[][] data = new Object[ary.size()][2];
for (int i = 0; i < ary.size(); i++) {
data[i][0] = ary.getJSONObject(i).getString("name");
data[i][1] = ary.getJSONObject(i).getString("pwd");
}
return data;
}