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

  • 相关阅读:
    求两个字符串中相同的汉字及字母的个数
    将十进制转成十六进制
    综合模糊查询
    求第一个字符串中第二个串的个数
    去除字符串中连续的分割符
    去除字符串中的html标记及标记中的内容
    sql基础语句
    SQL Server2008函数大全(完整版)
    sql 数字转人民币大写函数(两种方法)
    数字转IP地址函数
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/14230330.html
Copyright © 2011-2022 走看看