jmeter压测学习35-添加 BeanShell 断言
前言
jmeter 的断言插件有很多,如果我们想提取返回的json值里面的内容去断言,可以用到 BeanShell 断言
BeanShell 断言
在请求后添加-断言-BeanShell 断言
接口返回的json内容
{
"code":0,
"msg":"login success!",
"username":"test",
"token":"8d67474dacf7e6df014183b604c58ffe5a8e144f"
}
解析json
在 BeanShell断言添加解析json的脚本,prev是表示当前的请求对象,从prev获取返回的数据,然后json解析提取对应的值
import org.json.JSONObject;
import org.json.JSONArray;
String response = prev.getResponseDataAsString();
JSONObject responseJson = new JSONObject(response);
String msg = responseJson.getString("msg");
log.info("msg的值:" + msg);
运行后会报错:Typed variable declaration : Class: JSONObject not found in namespace
2021-01-04 15:02:34,634 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file:
inline evaluation of: ``import org.json.JSONObject; import org.json.JSONArray;
String response = prev. . . . '' :
Typed variable declaration : Class: JSONObject not found in namespace
2021-01-04 15:02:34,635 WARN o.a.j.a.BeanShellAssertion: org.apache.jorphan.util.JMeterException:
Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.json.JSONObject;
import org.json.JSONArray; String response = prev. . . . '' :
Typed variable declaration : Class: JSONObject not found in namespace
这个是因为没有json.jar包,需自己下载一个json.jar放到jmeter的lib目录下
json.jar放到jmeter的lib目录下后重启jmeter ,再次运行就可以看到获取到返回的值了
添加断言
添加断言,判断获取的字符串跟预期的字符串相等"login success!"。
import org.json.JSONObject;
import org.json.JSONArray;
String response = prev.getResponseDataAsString();
JSONObject responseJson = new JSONObject(response);
String msg = responseJson.getString("msg");
log.info("msg的值:" + msg);
//添加断言
if (!msg.equals("login success!")) {
log.info("接口返回:"+response);
Failure=true ;
FailureMessage = "断言失败,返回的内容:"+msg;
return;
}
判断相等用msg.equals("预期结果"),判断不相等前面加!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-01-04 Linux学习8-CentOS部署自己本地的django项目
2019-01-04 关于面试总结12-接口自动化面试题