Skip to content

Java Beanshell语法与内置对象

Java-Beanshell 语法与内置对象

简介

Beanshell 的语法结构在很大程度上与 Java 保持一致,因此掌握 Java 编程的开发者可以相对容易地上手 Beanshell。Beanshell 是一种动态解释执行的脚本语言,它允许直接运行源代码而无需事先编译成字节码。这一特性使得 Beanshell 在需要快速原型设计、测试或执行动态代码片段的场景中特别有用。

Beanshell内置对象-log

  • 日志对象:可以将日志内容记录到$jemeter_path/bin/jmeter.log
  • 实战举例: 1. 添加新的线程组 alt text 2. 添加BeanshellSampler alt text 3. 添加监听器 alt text 4. 运行查看结果 示例代码: log.info(" ====> Test log"); 结果: alt text

Beanshell内置对象-vars

  • 内置对象:可以操作jmeter变量,提供读取/写入访问变量的方法
  • 常用方法
    • vars.put(String key,String value):数据存储到jmeter变量中
    • vars.get(String key):从jmeter中获取变量值 示例代码

      vars.put("key1","value1");
      String key1 = vars.get("key1");
      log.info("====> key1"+key1);
      
      参考结果 alt text - Debug Sampler: alt text

Beanshell内置对象-ctx

  • 上下文对象:通过它可以访问当前线程的上下文context,列:获取上下文属性ctx.getProperties();
  • api文档:https://jmeter.apache.org/api/org/apache/jmeter/threads/JMeterContext.html
  • 实战举例: 示例代码
    Properties props = ctx.getProperties();
    log.info("====== properties ======>" + props);
    
    alt text

Beanshell内置对象-props

  • 内置对象:操作JMeter属性,参数从文件jmeter.properties 读入
  • 实战举例: 示例代码

String encoding = props.get("sampleresult.default.encoding");
log.info("=====>" + encoding);
alt text

Beanshell内置对象-prev

  • 获取前面取样器的SampleResult返回值,在使用之前必须有一个取样器且有对应的返回值,否则会返回空值,列:获取前面取样器相应返回值prevent。个体Response Code();
  • api参考文档:https://jmeter.apache.org/api/org/apache/jmeter/samplers/SampleResult.html
  • 实战举例:
    • 新建Http请求 alt text 示例代码
      String resp_code = prev.getResponseCode();
      log.info("=====>response code :" + resp_code);
      
    • 结果展示 alt text

Beanshell内置对象-bsh.args

  • 获取当前beanshell运行的传入参数,列:引用变量bsh.args[0],bsh.args[1];
  • 实战举例: 示例代码:
    log.info("======>" + bsh.args[0] + "&" + bsh.args[1]);
    
    结果展示: alt text

总结

  • Beanshell 简介
  • Beanshell内置对象-log
  • Beanshell内置对象-vars
  • Beanshell内置对象-props
  • Beanshell内置对象-prev
  • Beanshell内置对象-bsh.args