Test a code block of an article without showing bugs

Note: Part of the information in this article is excerpted from

  • Source: http://www.cnblogs.com/puresoul/p/4915350.html
  • Source: http://www.cnblogs.com/puresoul/p/4949889.html
  • Source: http://blog.csdn.net/silencemylove/article/details/51373873

1. What is Bean Shell

  • BeanShell is a scripting language that fully complies with the Java syntax specification, and has its own syntax and methods;
  • BeanShell is a loosely typed scripting language (similar to JS);
  • BeanShell is written in Java, a small, free, downloadable, embedded Java source code interpreter with object scripting language features, and a very compact interpreter jar file size of 175k.
  • BeanShell executes standard Java statements and expressions, in addition to some scripting commands and syntax.

Official website: http://www.BeanShell.org/

 

2. What Bean Shells does Jmeter have?

  • Timer: BeanShell Timer

  • Preprocessor: BeanShell PreProcessor

  • Sampler: BeanShell Sampler

  • Post-processor: BeanShell PostProcessor

  • Assertions: BeanShell Assertions

  • Listener: BeanShell Listener

 

Third, the usage of BeanShell

   The usage of BeanShell PreProcessor is introduced here, and other beahshells can be analogized. Here we use beahshell to call the tool class written by ourselves. The tool class implements the encryption and decryption functions of the password:

1. Write the code in eclipse, and then type the class into a jar package (right-click on the class->Export->jar file) The ar package is placed in the jmeter directory \apache-jmeter-2.13\lib\ext

3、打开jmeter,添加一个http sampler(调用登录接口),在sampler下添加一个BeanShell PreProcessor(如果jmeter已经打开了,步骤2中jar包要生效,必须才重启jmeter

4、在beanshell PreProcessor中导入我们的jar包,调用里面的加、解密码方法,把结果保存在jmeter变量中,下面两个方法是beanshell中我们最常用到的:

  • vars.get(String paramStr):获得变量值
  • vars.put(String key,String value):,将数据存到jmeter变量中

import com.pingan.ff.account.user.utils.*;

//加密
System.out.println("*****加密*****");
String password = "123123";
String encode = SecurityUtils.getKey(password);//调用工具类中的方法进行加密
System.out.println("Set my encode");
vars.put("encode",encode);//把值保存到jmeter变量encode中
String getEncode=vars.get("encode");
System.out.println("Get my encode: " + getEncode);

5、把加密后的密码存到jmeter变量中,然后在http sampler中就可以通过${encode}进行使用了:

6、执行脚本:

 

四、Bean Shell常用内置变量

    JMeter在它的BeanShell中内置了变量,用户可以通过这些变量与JMeter进行交互,其中主要的变量及其使用方法如下:

  • log:写入信息到jmeber.log文件,使用方法:log.info(“This is log info!”);

  • ctx:该变量引用了当前线程的上下文,使用方法可参考:org.apache.jmeter.threads.JMeterContext

  • vars - (JMeterVariables):操作jmeter变量,这个变量实际引用了JMeter线程中的局部变量容器(本质上是Map),它是测试用例与BeanShell交互的桥梁,常用方法:

    a) vars.get(String key):从jmeter中获得变量值

    b) vars.put(String key,String value):数据存到jmeter变量中

    更多方法可参考:org.apache.jmeter.threads.JMeterVariables

  • props - (JMeterProperties - class java.util.Properties):操作jmeter属性,该变量引用了JMeter的配置信息,可以获取Jmeter的属性,它的使用方法与vars类似,但是只能put进去String类型的值,而不能是一个对象。对应于java.util.Properties。 

    a) props.get("START.HMS");  注:START.HMS为属性名,在文件jmeter.properties中定义 

    b) props.put("PROP1","1234"); 

  • prev - (SampleResult):获取前面的sample返回的信息,常用方法:

    a) getResponseDataAsString():获取响应信息

    b) getResponseCode() :获取响应code

    更多方法可参考:org.apache.jmeter.samplers.SampleResult

  • sampler - (Sampler):gives access to the current sampler

     

五、自定义函数

  在BeanShell中,我们可以使用java语言自定义函数来处理特定的逻辑,结合BeanShell的内置对象进行变量的存取,方便我们进行测试提高脚本的灵活性。

示例:

1、在Test Plan中添加一个变量:hello = kitty

 

2、Debug sampler-1和Debug sampler-2什么都不处理,用来查询对比beahshell处理前后的结果

3、BeanShell Sampler中的脚本如下:

 

4、运行结果:

  • Debug sampler-1中显示:hello=kitty
  • BeanShell sampler中 返回结果为:success 
  • Debug sampler-1中显示:hello=world,jmeter=111111

 

 

  有没有觉得上面(三)中自定义函数这样的方式太麻烦并且也不美观?而且如果我们已经有现成的java源文件或者class文件时,我们有没有什么办法直接在jemter中引用?这就是这部分要介绍的内容,直接上示例:

1、假如我有一个java 源文件,名为:Myclass.java,代码如下: 

 

package test;
public class Myclass
{
    public int add(int a, int b)
    {
        return a + b;
    }    
}

 2、Bean Shell使用代码如下:

  在bean shel中通过source("代码路径")方法引入java,然后调用方法和java一样,new一个class,再调用里面的add 方法。

3、运行结果:

 

七、引用外部class文件

  现在知道如何引用外部文件,有时候如果我们只有class文件怎么办呢?其实在jmeter中也可以直接引用class文件,示例如下:

1、直接把上例中的java文件编译成class文件,如何编译请自行百度。

2、Bean Shell使用代码如下:

  用addClassPath("D:\\")方法引入 class文件,在用import导入包及类,然后就可以像java一样调用了

3、运行结果:

 

八、引用外部Jar包

  上面四、五介绍了如何引用外部java和class文件,如果文件比较多时我们可以把它们打成一个jar包然后在jemter中调用,具体如何使用可以看我上一篇有介绍:Jmeter之Bean shell使用(一)

  在这里想补充一点的是jmeter中引入jar的方法:

  1、上一篇中已使用过的:把jar包放到jmeter目录\apache-jmeter-2.13\lib\ext下

  2、在Test Plan的右侧面板最下方直接添加需要引用的jar包,如下图:

 

九、其它用法

1、在Test Plan中定义如下三个变量:

2、Bean Shell可脚本如下:

  a、bean shell可以接受传入参数,如下图:${u1} ${u2} ${u3}

  b、参数可以通过bsh.args[]按顺序提取

  c、bean shell提供了一个内置变量Parameters,来保存参数的集合

3、运行结果:

下图中1输入的这两句设置:

ResponseCode = 500;
ResponseMessage = "This is a test";

下图中2输入的这两句设置:

log.info(Parameters);

log.info(Label);

 十、提取json数据

需求:提取sample返回json数据中所有name字段值,返回的json格式如下: 

{“body”:{“apps”:[{“name”:”111”},{“name”:”222”}]}} 

jmeter中添加后置处理器BeanShell PostProcessor 

说明:脚本中的导入的json包需要自己去网络下载后放到\lib\ext,请悉知

这里写图片描述 
这里写图片描述

import org.json.*;

String response_data = prev.getResponseDataAsString();
JSONObject data_obj = new JSONObject(response_data);
String apps_str = data_obj.get("body").get("apps").toString();
JSONArray apps_array = new JSONArray(apps_str);
String[] result = new String[apps_array.length()];
for(int i=0;i<apps_array.length();i++){
    JSONObject app_obj = new JSONObject(apps_array.get(i).toString());
    String name = app_obj.get("name").toString();
    result[i] = name;
}
vars.put("result", Arrays.toString(result));

十一、断言

import txtWrite.*;
String response_data = prev.getResponseDataAsString();
String assert_data="科目${num}";
TxtWrite writeData=new TxtWrite();
if(response_data.indexOf(assert_data)!=-1)//请求的response中有包含自定义字符,则断言结果为false
{
    Failure=false;
    String message="${__time(yyyy-MM-dd HH:mm:ss,)}   新建科目【"+assert_data+"】成功";
    FailureMessage=message;
    writeData.contentToTxt("D:/xykyInterfaceAutoTest.log",message);
    
}else
{
    Failure=true;
    String message="${__time(yyyy-MM-dd HH:mm:ss,)}   新建科目【"+assert_data+"】失败----------";
    String response="本次请求response数据:"+prev.getResponseDataAsString()+"----------";
    String need_assert="需要断言的数据:"+assert_data;
    FailureMessage=message+response+need_assert;
    writeData.contentToTxt("D:/xykyInterfaceAutoTest.log",message+response+need_assert);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325455681&siteId=291194637