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("预期结果"),判断不相等前面加!

原文地址:https://www.cnblogs.com/yoyoketang/p/14230330.html