JMeter接口测试系列-关联参数

这里主要记录一下A接口的返回结果经过md5加密之后作为另外B接口的参数,这个问题困扰了很久,找了不少资料,现在把解决方法记录如下:

环境

①JMeter 3.0

②前置条件:将fastjson.jar包置于..apache-jmeter-3.2lib下,并将该jar包添加到测试计划的Library中;否则会报:Typed variable declaration : Class: JSONObject not found in namespace的错误;

fastjson.jar包下载地址:https://github.com/alibaba/fastjson

③处理器:Beanshell处理器,import com.alibaba.fastjson.JSON;(一般习惯使用到什么import什么,如:import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;这里需要用到[import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;])

实现目标:

A接口的响应结果result ,经过MD5(result+a+B+c+D)=ptoken,加密结果ptoken作为B接口的一个参数。

如何实现?

  1. 在A接口之后首先添加使用BeanShell PostProcessor(后置处理器),使用后置处理器获取响应结果result的值;
  2. 在B接口中添加BeanShellSampler,导入md5加密的jar包,然后将返回的result+customerCode_timestamp+ytoken(这里说明一下customerCode、timestamp、ytoken已经在测试计划用户定义的变量添加)经过加密之后作为B接口的一个参数

下面是根据上面的思路完成的实际操作
这里是测试计划-用户定义的变量如图

  1. 在A接口中添加后置处理器截图所示

响应结果的字符串形式如图

这里需要提取result的值G0444260257
代码如下:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

String json = prev.getResponseDataAsString(); //获取登录请求的响应信息
log.info("json="+json);
//利用上一步获取的字符串形式的JSON,结合Java处理Json的方法,将需要的键值提取出来;
JSONObject jso = JSON.parseObject(json);

String res = jso.getString("result");
log.info("res="+res);
//保存提取的结果为res
vars.put("res",res);

然后添加一个BeanShell Sampler 计算md5加密之后,将值作为B接口的参数
BeanShell Sampler的代码如下

import com.test.mymd5;

//undefined customerCode
String customerCode = vars.get("customerCode");
//定义时间戳
String timestamp = vars.get("timestamp");
//定义机构中的serial_number_md5,临时会话验证
String ytoken = vars.get("ytoken");
String rest = vars.get("res");


//定义英文下划线_ underscores 
String underscores = vars.get("underscores");
log.info("underscores="+underscores);

log.info("customerCode="+customerCode);
log.info("timestamp="+timestamp);
log.info("rest="+rest);
log.info("ytoken="+ytoken);

String ptoken = mymd5.md5(rest+customerCode+underscores+timestamp+ytoken);
vars.put("ptoken",ptoken);
log.info("ptoken="+ptoken);

System.out.println(ptoken);
System.out.println(rest);

那么接下来就是接口B参数的使用,这个可以使用${参数名}来直接使用该参数,如图

这样接口参数都配置完成,如何增加断言该接口是成功的呢?
这里使用的是jmeter中的响应断言,配置如图所示

这里断言的是接口响应结果code为0。

关联参数我们上面使用的是BeanShell PostProcessor获取接口的响应结果。其实,我们也可以使用正则表达式或是jp@gc-JSON Path Extractor提取接口的响应结果作为下一个接口的参数,如图配置的正则表达式和jp@gc-JSON Path Extractor提取:

而使用jp@gc-JSON Path Assertion断言响应结果是否正确(和响应断言功能一致,也path extractor配合使用),配置如图

但是这里提取的响应结果是正确的,使用md5加密的时候,显示该参数是null,所以这里留了一个尾巴,暂时还没好的解决方法?

参考

博客:https://www.cnblogs.com/xpp142857/p/7374281.html

原文地址:https://www.cnblogs.com/LOVEYU/p/8045148.html