jmeter testing java code

Sometimes you always have to write code. You have to be able to write code. If you don't look down on java requests, you need to write code. First, implement a class,

   

package com.company.jemeters;

public class Hello {
    public int sum(int a,int b)
    {
        return a+b;
    }
}

To implement an addition, let's write the test class

You need to add jemter's library to lib

package com.company.jemeters;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

public class perftest extends AbstractJavaSamplerClient  {
    private  String a;
    private  String b;
    private  String resultData;
    public Arguments getDefaultParmeters(){
        Arguments params=new Arguments();
        params.addArgument("num1","");
        params.addArgument("num2","");
        return params;
    }
    public  void  setupTest(JavaSamplerContext arg0){
    }
    public SampleResult runTest(JavaSamplerContext arg0){
        a=arg0.getParameter("num1");
        b=arg0.getParameter("num2");
        SampleResult str= new SampleResult();
        str.setSampleLabel("java request");
        try{
            str.sampleStart();// jmeter Start statistics response time tag
            Hello test = new Hello();
            // The response of the tested method can be output to the Jmeter The response data in the result tree.
            resultData = String.valueOf(test.sum(Integer.parseInt(a), Integer
                    .parseInt(b)));
            if (resultData != null && resultData.length() > 0) {
                str.setResponseData("The result is:"+resultData, null);
                str.setDataType(SampleResult.TEXT);
            }
            System.out.println(resultData);
            str.setSuccessful(true);
        }catch (Throwable e){
            str.setSuccessful(false);
        }finally {
            str.sampleEnd();
        }
    return str;
    }
    public  void  teardownTest(JavaSamplerContext arg0){

    }
}

After that, we will start to test the jar package,

Put it in jemter's \ lib\ext file,

Open jmeter, create a new java request,

 

Then click Run

So we have finished jmeter testing java classes. Isn't it very simple? In fact, this is just the beginning.

Tags: Java Apache

Posted on Wed, 01 Apr 2020 11:16:13 -0700 by rahnel