zoukankan      html  css  js  c++  java
  • Jmeter接口测试使用beanshell断言json返回

    一般情况下响应断言就能解决很多问题,但是返回复杂的json时就需要用到beanshell断言。

    举个例子

    免费的接口API www.sojson.com/api/beian/sojson.com

    host:    www.sojson.com

    source:   api/beian/sojson.com (api/beian后面只能跟一级域名如:baidu.com或者sojson.com)

    创建好线程组HTTP请求,给该请求加beanshell断言,代码如下,其中必须加prev.setSuccessful(false);设置用例的结果

    beanshell代码如下

     1 import com.google.gson.JsonObject;    
     2 import com.google.gson.JsonParser;
     3 import java.lang.*;
     4 //获取上一个请求的返回
     5 response = prev.getResponseDataAsString(); 
     6 log.info(response);
     7 
     8 //正常情况的history应该为数据库查询出来的结果
     9 String history="{"nature":"企业","icp":"京ICP备16038595号","indexUrl":"www.sojson.com","sitename":"JSON在线解析","domain":" sojson.com ","nowIcp":"京ICP备16038595号-2","type":200,"search":"sojson.com","checkDate":"","name":"北京都芳商贸有限公司"}";
    10 //使用Gson解析json
    11 JsonParser parser = new JsonParser();    
    12 JsonObject responseObj = (JsonObject) parser.parse(response);
    13 
    14 JsonParser parser1 = new JsonParser();            
    15 JsonObject historyObj = (JsonObject) parser1.parse(history); 
    16 
    17 if(history == "")  
    18 {  
    19 //    Failure = true;  
    20     FailureMessage = "连接数据库失败或者数据库内没有历史数据";   
    21       
    22 //调用Gson提供的Json对象euqals方法判断是否一致  
    23 }else if(responseObj.equals(historyObj) == false)  
    24 {   
    25     log.info("不一样");
    26     //设置该条用例结果,但是查看结果树中不会打印出错信息FailureMessage
    27     prev.setSuccessful(false);
    28 //把断言失败置为真,即用例失败,并在结果树中显示FailureMessage 
    29 Failure = true;  
    30 FailureMessage = "请求返回和数据库不匹配";   
    31 }
    32 else
    33 {
    34     log.info("俩一模一样");    
    35     }
  • 相关阅读:
    java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized...
    Spring Security 自定义 登陆 权限验证
    springboot中使用spring security,登录url就出现403错误
    RocketMQ最佳实践
    JS 中获取服务器时间的注意点
    许小年:中国经济刚入寒冬,四万亿也救不了
    RestTemplate发送GET请求
    String类的format方法的用法
    参数的打包和解包实例
    16.return 返回值
  • 原文地址:https://www.cnblogs.com/gcgc/p/6816650.html
Copyright © 2011-2022 走看看