Jmeter二次开发函数之入门

背景:Jmeter不能满足我们的参数需求,如生成手机号码、身份证号码等业务,固对jmeter进行二次函数开发。

jmeter提供了接口供用户进行二次开发,我们只需引入包进行编辑。从jmeter规范上,我们建package包的命名必须functions结尾,并且建class的时候需引入jmeter的AbstractFunction类。

 

1、jmeter函数助手下拉框中现在没有helloword函数的,此文章将会实现在jmeter函数助手新增一个函数helloword,实现调用函数helloword则输出“hello,word!”的功能

2、我使用的java开发工具是eclipse,在eclipse新建一个 Java project命名为“newtest”

新建的“newtest”项目会自带一个src文件

在“newtest”项目右键Build Path->Configure Build Path->Libraries

点击“Add External JARs”添加jmeter目录下的jar依赖包 \apache-jmeter-5.5\lib\ext\ApacheJMeter_core.jar、ApacheJMeter_functions.jar

 

添加成功

 

3、在src文件下新建一个package命名为“org.apache.jmeter.functions”【注意package命名必须functions结尾】

4、在package “org.apache.jmeter.functions”下面新增class命名为“HelloWordFunction”并继承jmeter自带的AbstractFunction

搜索添加jmeter自带的abstractFunction

保存class

5、新建class成功HelloWordFunction.java,新class继承jmeter的AbstractFunction带出4个方法,函数开发就是在这4个方法上改造

4个方法分别在jmeter函数助手对应位置,最重要的部分是“execute”逻辑处理功能

6、进行一个简单函数编译,在HelloWordFunction.java初始代码上编辑这3行(逻辑为:命名一个key="__helloword",调用函数返回结果为"hello,word!")

 

package org.apache.jmeter.functions;

import java.util.Collection;
import java.util.List;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

public class HelloWordFunction extends AbstractFunction {
    //jmeter函数的名称必须要以“__”两个下滑杠开头
    private final static String key="__helloword";
    
    //用来定义函数的参数列表
    @Override
    public List<String> getArgumentDesc() {
        // TODO Auto-generated method stub
        return null;
    }

    //函数的结果由该方法来返回
    @Override
    public String execute(SampleResult arg0, Sampler arg1) throws InvalidVariableException {
        // TODO Auto-generated method stub
        return "hello,word!";
    }

    //函数的参数名称
    @Override
    public String getReferenceKey() {
        // TODO Auto-generated method stub
        return key;
    }

    //用来接收和处理用户传入的参数值
    @Override
    public void setParameters(Collection<CompoundVariable> arg0) throws InvalidVariableException {
        // TODO Auto-generated method stub

    }

}

7、将HelloWordFunction.java代码保存,右键导出

选择java->JAR file,点击next

保存jar包到本地 

8、将jar包拷贝到jmeter安装目录下的文件下\apache-jmeter-5.5\lib\ext\

9、重启jmeter,即可在函数助手下拉框中看到函数helloword

调用调函返回结果hello,word!

 

posted @ 2023-04-26 14:24  dabeen  阅读(320)  评论(0编辑  收藏  举报