方法一:
import org.json.*;
//获取响应状态码
String code = prev.getResponseCode();
System.out.println("code的值:" + code);
if (code.equals("${my_code}"))
{
//获取上一个请求的返回值
String response = prev.getResponseDataAsString();
//将返回值转换为json
JSONObject responseJson = new JSONObject(response);
//获取responseMsg
String msg = responseJson.getString("msg");
System.out.println("msg的值:" + msg);
if(!msg.equals("${my_msg}")) {
Failure = true;
FailureMessage = "规则解析失败";
}
else{
FailureMessage = "规则解析成功";
}
//获取responseCode
String code1 = responseJson.get("code").toString();
System.out.println("code的值:" + code1);
if(!code1.equals("${my_code1}")) {
Failure = true;
FailureMessage = "code非0";
}
else{
FailureMessage = "code为0";
}
//获取responseSuccess
String success = responseJson.get("success").toString();
System.out.println("success的值:" + success);
if(!success.equals("${my_success}")) {
Failure = true;
FailureMessage = "success为false";
}
else{
FailureMessage = "success为true";
}
}
else
{
Failure = true;
FailureMessage = "响应code与预期不符";
prev.setStopThread(true);
}
方法二: 先下载一个fastjson-1.2.49.jar 包,并将该包放在 D:\jmeter5.2\apache-jmeter-5.2.1\lib\ext 文件夹下
具体脚本如下:
`import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
//获取响应状态码
String code = prev.getResponseCode();
System.out.println("code的值:" + code);
if (code.equals("${my_code}"))
{
//获取上一个请求的返回值
String response = prev.getResponseDataAsString();
//将返回值转换为json
JSONObject responseJson= JSON.parseObject(response);
//获取responseMsg
String msg = responseJson.getString("msg");
System.out.println("msg的值:" + msg);
if(!msg.equals("${my_msg}")) {
Failure = true;
FailureMessage = "规则解析失败";
}
else{
FailureMessage = "规则解析成功";
}
//获取responseCode
String code1 = responseJson.get("code").toString();
System.out.println("code的值:" + code1);
if(!code1.equals("${my_code1}")) {
Failure = true;
FailureMessage = "code非0";
}
else{
FailureMessage = "code为0";
}
//获取responseSuccess
String success = responseJson.get("success").toString();
System.out.println("success的值:" + success);
if(!success.equals("${my_success}")) {
Failure = true;
FailureMessage = "success为false";
}
else{
FailureMessage = "success为true";
}
}
else
{
Failure = true;
FailureMessage = "响应code与预期不符";
prev.setStopThread(true);
}`
BeanShell断言