Jmeter

记录jmeter使用beanshell断言获取复杂的json字符

2020-09-11  本文已影响0人  Coding测试

实战示例

测试场景
库存余量查询响应结果

2、期望获取的结果

通过上面响应结果,想获取参数为periods数组下的period_stock参数值和back_periods数组period_stock参数值。
标注如下:


image

3、jmeter beanshell

测试获取建议操作

然后就只把把代码复制到beanshell中即可。在jmeter中可以打印下获取的库存余量,结果如下:


  import org.json.*;
  //获取上一个请求的返回值
  String response = prev.getResponseDataAsString();
  //将返回值转换为json
  JSONObject responseJson = new JSONObject(response);
  //获取responseMessage
  JSONArray data = responseJson.getJSONObject("data").getJSONArray("ticket_periods");
  JSONObject ticket_periods = (JSONObject)data.get(0);
  JSONObject periods =(JSONObject)(ticket_periods.getJSONArray("periods").get(0));
  Integer period_stock = periods.getInt("period_stock");
  JSONObject back_periods=(JSONObject)(ticket_periods.getJSONArray("back_periods").get(0));
  Integer  period_stock_back = back_periods.getInt("period_stock");
  log.info("==========获取库存开始===========");
  log.info("periods内余量值:" + period_stock);
  log.info("back_periods内余量值:" +period_stock_back);
  log.info("==========获取库存结束===========");
  //beanshell断言
 if(period_stock == 0){
   Failure = true; 
   FailureMessage = "period_stock的值:" + period_stock +"警告:已无库存,请注意查看"+ "||period_id的值为:"+period_stock_back+"警告:已无库存,请注意查看";
}
public void testCase() throws IOException {
//        //将返回值转换为json
//        JSONObject responseJson = new JSONObject(str);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        Map map = objectMapper.readValue(str, Map.class);
        Map dataMap = (Map) map.get("data");
        List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("ticket_periods");
        list.stream().forEach(item ->{
            List<Map<String, Object>> periodsList = (List<Map<String, Object>>) item.get("periods");
            periodsList.stream().forEach(periods ->{
                System.out.println("当前period_stock的值:"+periods.get("period_stock"));
            });
        });
    }

vars.put赋值,格式为 vars.put("key","value")
vars.get 获取变量,vars.get("period_stock")

2、特别说明:如果想把Integer类型通过vars放入的话需要加上toString()方法,上面需要把Integer 类型period_stock作为变量传递,示例

 vars.put("period_stock",period_stock.toString());

其它接口可通过变量名取值:{"period_stock":"${period_stock}"}
传递结果

GET http://127.0.0.1:8080/test

GET data:
{"period_stock":"80"}

[no cookies]

Request Headers:
Connection: keep-alive
Content-Type: application/json
Content-Length: 21
Host: 127.0.0.1:8080
User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_181)
上一篇下一篇

猜你喜欢

热点阅读