查询接口自动化测试,主要分为几步:
- 从数据库查询数据
- 随机取数作为接口的入参
- 调用接口
- 再次查询数据库,获取预期结果数据
- 比较接口返回和预期结果
注:如果接口入参有多个,需要考虑接口间的组合情况、必填参数和非必填参数之间的组合情况以及异常场景
简单的例子:
http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo
假设上面要调用的接口,数据来源为我本地数据库的mobilearea表。表结构如下:
第一步,从数据库查询数据
第二步,随机设置入参(在查询取样器后添加后置BeanShell处理器)
import java.util.Random;
//取出sql语句查询结果
Object result = vars.getObject("result");
int size = result.size();
//在查询结果中随机取一个作为入参
Random random=new Random();
if(size > 0){
int randomNum = random.nextInt(size);
String temp = result.get(randomNum).get("mobile");
log.info("=========================randomNum = " + randomNum.toString() + ", " + "mobile = " + temp);
vars.put("mobile",temp);
}
第三步,调用接口,并去除接口返回结果
此处的mobile即为上一步赋值的变量
后置BeanShell取出接口调用的结果
import org.json.* ;
//取接口调用返回
String response = prev.getResponseDataAsString();
JSONObject response1=XML.toJSONObject(response);
String CodeInfoResult = response1.get("soap:Envelope").get("soap:Body").get("getMobileCodeInfoResponse").get("getMobileCodeInfoResult");
String responseArea = CodeInfoResult.split(":")[1];
//将解析结果存在变量中
vars.put("responseArea",responseArea);
第四步,查询预期结果
添加后置BeanShell处理器,取出查询的预期结果,与接口调用的实际结果进行比较
//获取预期结果
Object expectResult = vars.getObject("expectResult");
String msg = "";
if(expectResult.size()>0){
String area = expectResult.get(0).get("area");
//获取接口返回的结果
String responseArea = vars.get("responseArea");
//比较接口调用结果和预期结果
if(responseArea.indexOf(area) != -1 ){
log.info("******************************Succes");
}
else{
msg = "expect: " + area + "But actual: " + responseArea;
}
}
vars.put("dataMessage",msg);
if(msg != ""){
log.error("*****************************Failed: " + msg);
}