前言
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("預期結果"),判斷不相等前面加!