在使用JMeter进行测试时,自带的函数可能不满足需求,这个时候需要自定义函数。
先建立Maven工程,然后修改pom.xml,引入JMeter相关jar包。
<dependencies>
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_functions</artifactId>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.jmeter</groupId>
<artifactId>ApacheJMeter_core</artifactId>
<version>5.1.1</version>
</dependency>
</dependencies>
接下来即可实现自定义函数。该类所在包必须是org.apache.jmeter.functions,然后继承org.apache.jmeter.functions.Abstractfunction,实现4个方法。
package org.apache.jmeter.functions;
import java.util.Collection;
import java.util.linkedList;
import java.util.List;
import org.apache.jmeter.engine.util.Compoundvariable;
import org.apache.jmeter.functions.Abstractfunction;
import org.apache.jmeter.functions.InvalidvariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
public class Testfunction extends Abstractfunction {
private static final List<String> argumentDesc = new linkedList<String>();
static {
argumentDesc.add("原始内容");
}
// function名称
private static final String KEY = "__Reverse";
private static final int PARAM_COUNT_MAX = 1;
private static final int PARAM_COUNT_MIN = 1;
// 传入参数的值
private Object[] values;
public List<String> getArgumentDesc() {
return argumentDesc;
}
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidvariableException {
String original = ((Compoundvariable) values[0]).execute().trim();
String result = reverse(original);
return result;
}
private String reverse(final String original) {
StringBuffer sbResult = new StringBuffer(original);
return sbResult.reverse().toString();
}
@Override
public String getReferenceKey() {
return KEY;
}
@Override
public void setParameters(Collection<Compoundvariable> parameters) throws InvalidvariableException {
// 检查参数的个数是否正确
checkParameterCount(parameters, PARAM_COUNT_MIN, PARAM_COUNT_MAX);
// 将值存入类变量中
values = parameters.toArray();
}
}
编写完代码后,使用Maven生成jar包,拷贝至$JMETER_HOME/lib/ext目录下,重新启动JMeter