jmeter统计接口返回json数据条数并断言

    最近公司在做jenkins持续集成,在自动化测试这步引入了jmeter作接口性能、功能测试。

    其中要实现某个业务需求:用jmeter对一个接口进行测试,该接口会以json形式固定返回63条数据,使用jmeter统计返回了多少条数据,并作出断言,如果数据条数不等于63条,则接口测试失败。返回数据如下:

1.添加后置BeanShell PostProcessor

 脚本文本:

import org.json.*;

String response_data = prev.getResponseDataAsString();
JSONArray apps_array = new JSONArray(response_data);
/*
 String[] result = new String[apps_array.length()];
for(int i=0;i<apps_array.length();i++){
    JSONObject app_obj = new JSONObject(apps_array.get(i).toString());
    String name = app_obj.get("gps_time").toString();
    result[i] = name;
}
vars.put("result", Arrays.toString(result));

 */
vars.put("sum",apps_array.length().toString());

2.引入需要的jar。此处需要引入json lib包(注意,这里是在Windows上写的脚本,lib也存在Windows的系统盘中) :

3.添加BeanShell Assertion

脚本文本:

int count=Integer.parseInt(vars.get("sum")); 
System.out.println(count);
if(count!=63){
	Failure=true;
	FailureMessage="数据条数不对";
}else{
	Failure=false;
	FailureMessage="测试通过";
}

 4.测试

控制台输出条数:

测试通过: 

修改脚本让测试不通过:

 此时在Windows上的脚本已经写好。

但是我们要运行在linux系统。lib包路径需要修改:

mkdir -p  /usr/local/jmeter/lib

上传lib包到此目录:

修改jmx中lib引用:

改为:

发布了70 篇原创文章 · 获赞 63 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/xiaoxiangzi520/article/details/88970458
今日推荐