jmeter beanshell postprocessor跨线程全局变量使用


最近开始使用jmeter做接口测试,遇到的主要问题在这里记录一下。

测试场景:

线程组1-登录-P1接口用例

线程组2-登录-P2接口用例

如果线程组1和2用同一个用户登录,线程组2用例执行会提示用户登录超时相关信息,这个时候就要考虑线程组1中的参数codeKey和loginCode能在线程组2中使用就解决问题了,另外一种没办法的办法就是用2个账号登陆,这样设置的全局变量数据不能共用了,也很麻烦。

1.线程组1中的参数保存到文件中,线程组2通过读取文件中的数据实现数据共享

线程组1登录用例添加后置处理器beanshell postprocessor。脚本内容如下:

String filePath = System.getProperty("user.dir") + "\\loginMsg.txt";
vars.put("filePath",filePath);
File file = new File(filePath);

try {
    if (file.exists()){
        file.delete();
    }
    file.createNewFile();
    FileWriter fs = new FileWriter(filePath,true);
    BufferedWriter bw = new BufferedWriter(fs);
    bw.write(vars.get("codeKey")+"?");

    bw.write(vars.get("loginCode"));
    bw.write(System.getProperty("line.separator"));
    fs.flush();
    bw.close();
    fs.close();
    
    
}catch(IOException e) {
    e.printStackTrace();
}
View Code

线程组2中通过csv数据文件设置读取文件中的数据,这个也可以实现,但个人觉得没必要这么麻烦。

2.通过函数助手__setProperty和后置处理器beanshell postprocessor实现跨线程参数共享

登录参数codeKey和loginCode

就是把通过正则获取到的${codeKey}值设置为全局变量,并以新的名字newcodeKey来引用

在登录请求添加后置处理器beanshell postprocessor

这样codeKey和loginCode就已经设置为全局变量了。发现用setProperty log中会报错显示变量未定义:ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``${codeKey}; ${loginCode}  : Attempt to access property on undefined variable or class name
WARN o.a.j.e.BeanShellPostProcessor: Problem in BeanShell script: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``${codeKey}; ${loginCode}  : Attempt to access property on undefined variable or class name

使用vars和props定义beanshell变量没问题,具体什么原因导致的,还不太清楚,有时间再研究一下。

props.put("newCodeKey",vars.get("CodeKey"));
props.put("newLoginCode",vars.get("LoginCode"));

线程组2中使用__P函数来调用以上参数:

这样就实现了多线程组共用同一账号登陆的场景。

避免线程组间用例执行顺序杂乱无章,在测试计划中勾选“独立运行每个线程组”:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM