zoukankan      html  css  js  c++  java
  • 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("预期结果"),判断不相等前面加!

  • 相关阅读:
    < java.util >-- Set接口
    Codeforces 627 A. XOR Equation (数学)
    Codeforces 161 B. Discounts (贪心)
    Codeforces 161 D. Distance in Tree (树dp)
    HDU 5534 Partial Tree (完全背包变形)
    HDU 5927 Auxiliary Set (dfs)
    Codeforces 27E. Number With The Given Amount Of Divisors (暴力)
    lght oj 1257
    Codeforces 219D. Choosing Capital for Treeland (树dp)
    Codeforces 479E. Riding in a Lift (dp + 前缀和优化)
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/14230330.html
Copyright © 2011-2022 走看看