使用Jmeter的BeanShell Sampler生成需要的参数

来源:互联网 发布:初中科学培训软件 编辑:程序博客网 时间:2024/05/15 10:47

 在Jmeter中个,有时候需要使用一些数据,但是通过jmeter自身或者通过关联无法得到,这个时候,可以使用Jmeter的BeanShell Sampler,然后使用BeanShell脚本语言生成需要的数据,举例如下:

------以下代码是生成当前时间1小时之前的时间

import bsh.EvalError;
import bsh.Interpreter;
import java.text.SimpleDateFormat;
import java.util.Date;
public static String dateAdd(String d) {
       if (d == null)
          return null;
       SimpleDateFormat format = new SimpleDateFormat("HHmmss");
       Date date = null;
       try {
          date = format.parse(d);
       } catch (Exception ex) {
       }
   
      
       long time = (date.getTime() / 1000);
       time = time - 1 * 3600;// 60 * 60 ;
       Date result = new Date();
       result.setTime(time * 1000);
      
       if (result != null) {
    String stime=format.format(result);
    System.out.print(stime);//可在启动jmeter的时候启动的那个控制台中看到输出的参数。

vars.put("time", stime);//把生成的结果放入vars中,脚本中直接用${time}可以获得stime的值。
                                 return stime;//需要return,否则会报错,暂时未研究为什么。

       }
       return null;
    }
dateAdd("${__time(HHmmss,)}");//${__time(HHmmss,)}函数功能:以()中的格式获得当前时间


补充:

如import java.text.SimpleDateFormat;
import java.util.Date;

此类import的包,可以根据java得知。

Response Assertion:

pattern to Test:中的表达式在response data中匹配到,return true;反之,return false;



JMeter在它的BeanShell中内置了变量,用户可以通过这些变量与JMeter进行交互,其中主要的变量及其使用方法如下(JMeter文档并没有对该部分内容进行详细讲解,这里也会说明他们分别对应于JavaDoc中的哪个类):

  • vars:这个变量实际引用了JMeter线程中的局部变量容器(本质上是Map),因此可以通过put和get方法访问JMeter中的变量。这个变量是所有内置变量中最有用的,它是测试用例与BeanShell交互的桥梁。对应于org.apache.jmeter.threads.JMeterVariables
  • props:该变量引用了JMeter的配置信息,它的使用方法与vars类似,但是只能put进去String类型的值,而不能是一个对象。对应于java.util.Properties。
  • ctx:该变量引用了当前线程的上下文,理论上通过这个东西我们几乎可以控制当前线程相关的一切,不过这要求使用者非常熟悉JMeter的源码。对应于org.apache.jmeter.threads.JMeterContext。
http://www.51testing.com/html/07/n-139507-2.html

小刀刀的博客,测试接口从零开始:http://www.51testing.com/?uid/128005

百度文库提供:如果网页上有登陆页面和身份验证,怎样去测试? 

JMeter