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

  • 相关阅读:
    知识搜索
    使用 getopt() 进行命令行处理
    【新提醒】夏新大v安卓4.1尝鲜最新更新版本发布(包含进步版)1124更新 大V综合交流区 360论坛
    搜狗知立方高调亮相 开启知识计算新时代
    socat: Linux / UNIX TCP Port Forwarder
    Crontab 每两周执行一次
    python 命令行解析 optionparser
    crontab jojo's blog--快乐忧伤都与你同在 BlogJava
    搜索引擎开始「实体搜索」新领域竞争,Google、百度分别发力实体搜索产品
    netcat(nc)的替代产品 Socat
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/14230330.html
Copyright © 2011-2022 走看看