Jmeter取样器之 Java Request


Jmeter取样器之 Java Request

请求Java类

实例

  1. 创建一个Java项目,并创建一个类,继承AbstractJavaSamplerClient,实现JavaSamplerClient
  2. 实现代码如下:
public class Demo extends AbstractJavaSamplerClient implements JavaSamplerClient{
        private String username;
        private String password;
        public Arguments getDefaultParameters() {
            Arguments args = new Arguments();
            args.addArgument("username","admin");
            args.addArgument("password","123");
            return args;
        }

        //每个线程测试前执行一次,做一些初始化工作;
        public void setupTest(JavaSamplerContext arg0) {
            //业务数据库连接
            username = arg0.getParameter("username");
            password = arg0.getParameter("password");
        }
        @Override
        public SampleResult runTest(JavaSamplerContext arg0) {
            SampleResult sr = new SampleResult();

            sr.setSampleLabel( "Java请求");
            sr.sampleStart();// jmeter 开始统计响应时间标记
            try {
                //运行内容
                sr.setResponseData("结果是:"+username+","+password, null);
                sr.setDataType(SampleResult.TEXT);
                sr.setSuccessful(true);
            } catch (Throwable e) {
                sr.setSuccessful(false);
                e.printStackTrace();
            } finally {
                sr.sampleEnd();// jmeter 结束统计响应时间标记
            }
            return sr;
        }
    }

注意:该类需引入Jmeter的jar包ApacheJMeter_core.jarApacheJMeter_java.jar,这两个jar包放置在JMETER_HOME\lib\ext目录下

  1. 将项目导出为jar包
  2. 将jar包添加到JMETER_HOME\lib\ext目录下,重启Jmeter
  3. 添加Java Request,选择类名
  4. 添加查看结果树,在响应数据中输出结果如下:
结果是:admin,123