1. BeanShell built-in variables
1. Beanshell can execute standard JAVA statements and expressions , and also includes some script commands and syntax
2. Support beanshell parts
- Preprocessor: BeanShell PreProcesser
- Sampler: BeanShell Sampler
- Post-processor: BeanShell PostProcesser
- Affirmations: BeanShell Affirmations
3. Built-in variables :
sampler position:
view the position of beanshell output: click the triangle icon
- log: write logs to the console and jmeter.log, such as log.info("xxxxx");
- vars: operate jmeter variables
- vars.get("port"): Get the value of ${skuId} variable from jmeter
- vars.put("name","test"): Save "test" to the ${name} variable
- prev: Get the information returned by the previous sampler
- getResponseDataAsString(): Get response information
- getResponseCode(): Get response code
More built-in variable reference: https://jmeter.apache.org
2. How to use BeanShell
Add beanshell script location: add → preprocessor/postprocessor → beanshell preprocesspr/postprocessor
2.1 Method 1: Write directly in JMeter
Disadvantages: JMeter cannot debug, no errors are reported, and it is difficult to locate bugs.
1、调用接口获取库存信息
2、判断库存,如果库存大于500,调用buy接口购买10个商品,否则购买5个商品 // 获取接口返回的库存值
String myStock = vars.get(“p_stock”);
// 转换为整数
int iStock = Integer.parseInt(myStock);
// 判断库存
2.2 Method 2: Introduce external JAVA source files
// 引入源文件
source("D:/test.java")
String num = "${__Random(10,600,)}" # num变量不可再除当前beanshell的任何文件下使用
// 生成随机手机号
String num2 = "135${__Random(10000000,99999999,myPhone)}";
String code = "wheat";
// 生成时间戳
String time = "${__time(,myTime)}";
// 调用外部函数进行加密
String md5 = Md5Util.getMd5Hex(phone+code+time); // 将数据另存为新的变量
//把数据存下来,就可在jmeter中的脚本中调用啦~
vars.put("num2",num2);
vars.put("md5",md5);
2.3 Method 3: Reference external jar package
The biggest difference from method two is the way of introduction. The jar package uses import to introduce
the decompilation tool jd-gui.
2.4 Assertion
Failure: Whether it failed, Boolean type
FailureMessage: Failure log, displayed when the assertion fails
int num = Integer.parseInt(var.get("nums"));
if (num > 50 ){
Failure = true;
FailureMessage = "库存低于50"; // 使用FailureMessage可自定义失败信息
log.info(new String(ResponseData));// ResponseData是写死的失败信息
log.info(SamplerData); // 打印请求数据
}else{
Failure = false;
}
Effect
2.5 Write data to file
Write the response data that needs to be written in the BeanShell post-processor. Remember to extract each data.
String line = vars.get("name")+","+vars.get("token");
try{
BufferedWriter writer = new BufferedWriter(new FileWriter("文件绝对路径",true));
writer.write(line);
writer.newLine();
writer.close();
} catch(IOException e){
e.printStackTrace();
}