1. 程式人生 > 實用技巧 >BeanShell斷言

BeanShell斷言

方法一:

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);
}