预置条件
1、开发工具
IntelliJ IDEA
2、依赖库
ApacheJMeter_core.jar
ApacheJMeter_java.jar
(存在于apache-jmeter-x.x.x\lib\ext目录下,将两文件复制到jdk1.8.0_xxx\jre\lib\extj目录下)
实现步骤
1、打开IntelliJ,新建1个Maven项目
2、在src/main/java目录下新增1个com.jmeter.functions目录,再在com.jmeter.functions下新增1个java文件
3、可参考源码:https://github.com/apache/jmeter/blob/master/src/functions/src/main/java/org/apache/jmeter/functions下java文件,来编写自定义函数。以下是我个人实现的自定义函数。
package com.jmeter.functions;
import java.lang.String;
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 APIAuthextends AbstractFunction {
//自定义function的参数名称
private static final List<String> args =new LinkedList<>();
//function名称
private static final String KEY ="__getAuth";
private static final int MAX_PARA_COUNT =3;//参数最多3个
private static final int MIN_PARA_COUNT =2;//参数最少2个
static {
//通过add方法可以添一个参数
//需添加多个参数时,多次调用即可添加多个参数
args.add("AppKey");
args.add("AppSecret");
args.add("Type");
}
public APIAuth() { }
//传入参数的值
private Object[] values;
@Override
public List getArgumentDesc() {
return args;
}
@Override
public String execute(SampleResult previousResult, Sampler currentSampler)throws InvalidVariableException {
try {
String userName = ((CompoundVariable)values[0]).execute();
String secret = ((CompoundVariable)values[1]).execute();
String type = ((CompoundVariable)values[2]).execute();
return getAuth(userName, secret, type);
}catch(Exception ex) {
throw new InvalidVariableException(ex);
}
}
@Override
public String getReferenceKey() {
return KEY;//方法名称
}
private String getAuth(String userName, String secret, String type){
//Write Your Code
}
@Override
public void setParameters(Collection parameters)throws InvalidVariableException {
checkParameterCount(parameters,MIN_PARA_COUNT,MAX_PARA_COUNT); //检查参数的个数是否正确
values = parameters.toArray(); //将值存入类变量中
}
}
4、生成jar包
a. File->Project Structure ->Artifaces ->"+" ->JAR->From modules with dependencies...,最后点"ok"。
b. Build ->Build Artifacts,最后点击Build。默认out目录下会存在一个jar包