JMeter performance test How to write Java request test Case Class __java

Source: Internet
Author: User
Tags documentation pack reflection
I. Introduction:

A recent project requires performance testing, which consists of several applications offering services, the framework of which is Alibaba's open source service Framework Dubbo. About the introduction of Dubbo, the Internet also has a lot of information, I just did a rough understanding, there is no in-depth study, the relevant information address is as follows: http://www.iteye.com/magazines/103,http://alibaba.github.io/ dubbo-doc-static/user+guide-zh.htm#userguide-zh-%e6%80%a7%e8%83%bd%e6%b5%8b%e8%af%95%e6%8a%a5%e5%91%8a,http:// Www.oschina.net/p/dubbo, application examples (including source code): http://blog.csdn.net/wilsonke/article/details/39896595,http:// download.csdn.net/detail/u012049463/6338227

Jmeter (official website: http://jmeter.apache.org/download_jmeter.cgi) as an open source of performance testing tools, provides detailed user operation manuals, demo and API documentation, has always been our first choice to do performance testing, However, most of the previous work is the HTTP request test, the interface form of the Java request Test has not been practiced. The quickest way to learn is to find examples from the internet, according to gourd painting gourd, it is true that I did so, although there are a lot of similar posts on the Internet, but here still want to make a record of their own practice process. ^^ Two. Text: 1. How to write Java Test class for JMeter interface test

In fact, JMeter has provided us with a framework for the Java Sampler test case class, which we can see in the API documentation (the apache-jmeter-2.11/docs/api/index.html path of the package) The Org.apache.jmeter.protocol.java.sampler package has an interface Javasamplerclient and an abstract class Abstractjavasamplerclient, our test case class simply implements the interface it provides or inherits the abstract class directly.

the Javasamplerclient interface defines four methods:

Getdefaultparameters () is used to get the parameters of the interface; Runtest (Javasamplercontext context) is used to write specific test cases, similar to the LR action, In the abstract class abstractjavasamplerclient does not write the implementation of the method, the test case is of course to write our own implementation; Setuptest (Javasamplercontext context) initialization method, The Setup () Teardowntest (Javasamplercontext context) in LR-like Init and JUnit is similar to the LR End and teardown () in JUnit.

With so much to say, it's time to use the example on the Internet (http://download.csdn.net/detail/u012049463/6338227) to illustrate, create a new Java project (preferably a MAVEN project, so it's easy to pack), Introduce the Lib\ext base package in JMeter: Apachejmeter_java.jar, Apachejmeter_core.jar can start writing test classes.

In this case, the service interface provided by the service side and the specific implementation class

Package com.huangjie.dubbo_Service.service;
Public interface Iprocessdata {public  
    string Setage (string age);  
    public string Sayhi (string name);  
Package Com.huangjie.dubbo_Service.service.impl;

Import Com.huangjie.dubbo_Service.service.IProcessData;

public class Processdataimpl implements Iprocessdata {  
     /* * @see com.xxx.bubbo.provider.iprocessdata#deal ( java.lang.String) 
     */  
    @Override public
    String setage (string age) {  
        try {  
            thread.sleep (1000);  
        catch (Interruptedexception e) {  
            e.printstacktrace ();  
        }  
        Return ' you are ' + Age + ' years old! ';  
    }  
    @Override public
    String sayhi (string name) {  
        try {  
            thread.sleep (1000);  
        } catch ( Interruptedexception e) {  
            e.printstacktrace ();  
        }  
        Return "Hi:" + name;  
    }  

Client Javasampler test Case class

Package Com.huangjie.dubbo_Consumer;
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;
Import Org.apache.log.Logger;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Import Com.huangjie.dubbo_Service.service.IProcessData; public class Jmeterinterfacetest extends abstractjavasamplerclient{private static String Label_name = "Dubbo_consume R "//define label name, display in JMeter result window private static final Classpathxmlapplicationcontext context = new CLASSPATHXMLAPPL 
    Icationcontext ("Classpath*:applicationconsumer.xml");
    private static Iprocessdata demoservice = null;
    Private Logger log = GetLogger ();
        @Override public void Setuptest (Javasamplercontext arg0) {log.info ("test case begins executing ..."); Define test initial values, setuptest use Demoservice = (iprocessdata) only before the test starts contExt.getbean ("Demoservice"); @Override public Arguments getdefaultparameters () {//parameter definitions, displayed in the foreground, or Arguments params = new       
        Arguments ();
        Params.addargument ("name", "Tom");
        Params.addargument ("Age", "23");
    return params;
        @Override public Sampleresult runtest (Javasamplercontext arg0) {Boolean success = true;
        Sampleresult sr = new Sampleresult ();
        Sr.setsamplelabel (Label_name);
            Sr.samplestart ()//is used to count execution time--start--try {String name = Arg0.getparameter (' name ');
            String msg = demoservice.sayhi (name);
            Thread.Sleep (5000);
            SYSTEM.OUT.PRINTLN (msg);
            Sr.setresponsemessage (msg);
        Sr.setresponsecode ("1000");
        catch (Exception e) {success = false;
        }finally{sr.sampleend ()//To count the execution time--end--sr.setsuccessful (success);
    } return SR;
    
    }@Override public void Teardowntest (Javasamplercontext arg0) {log.info ("End of test case execution ..."); }

}

Description

First, the Getdefaultparameters () method is used to define the parameters, where we define the name and age two parameters and assign the default value "Tom" and "23" so that you can see these two parameters in the Java request created by JMeter Selecting the above test class. and the parameter value can be arbitrarily modified.

Then, looking closely, we find that the test class contains only the Sayhi () method, and does not invoke the Setage () method provided by the server, and the reason why we do not call two test methods inside a test case is because our purpose here is to test a single scenario, That is, if you want to test the two methods separately, then you have to build a testing case class, the other parts of the code can be unchanged, as long as the implementation of the method to replace it. Therefore, we will think that if an interface provides n methods, then we will write a similar n classes, although copying and pasting is easy, but this will produce a heap of class files, feel very redundant, here can use the Java reflection mechanism to implement the dynamic invocation of the method. Simply put, in the Runtest () method, the method is not written to kill the specific use case call, but is determined by the Java reflection mechanism by input parameters. Rewrite the above test case class as follows:

Write an abstract class to inherit abstractjavasamplerclient, which writes only the dynamically invoked method, and other methods are overridden in the use case class.

Package Com.huangjie.dubbo_Consumer;
Import java.lang.reflect.InvocationTargetException;

Import Java.lang.reflect.Method;
Import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
Import Org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;

Import Org.apache.jmeter.samplers.SampleResult;  Public abstract class Abstractserviceclient extends abstractjavasamplerclient{the public Object invokeruntest (String TestName, Javasamplercontext context, Sampleresult Sampleresult) {method[] methods = This.getclass ()
        . GetMethods ();
                    For (method Method:methods) {if (Method.getname (). Equalsignorecase (testname)) {try {
                Return Method.invoke (this, context, sampleresult);
                catch (IllegalArgumentException e) {e.printstacktrace ();
                catch (Illegalaccessexception e) {e.printstacktrace (); catch (InvocationtargetException e) {e.printstacktrace ();
    }} return null; }
    
}

Test Case class inherits the abstract class of the dynamic method call above

Package Com.huangjie.dubbo_Consumer;
Import org.apache.jmeter.config.Arguments;
Import Org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
Import Org.apache.jmeter.samplers.SampleResult;

Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Import Com.huangjie.dubbo_Service.service.IProcessData; public class Dynamicmethodinvoketest extends abstractserviceclient{private static String Label_name = "Dubbo_consume R "//define label name, displayed in JMeter result window private static final Classpathxmlapplicationcontext CXT = new Classpathxmlapplicat 
    Ioncontext ("Classpath*:applicationconsumer.xml");
    
    private static Iprocessdata demoservice = null; @Override public void Setuptest (Javasamplercontext context) {//define test initial values, setuptest use Super.setup only before the test starts
        Test (context);
    Demoservice = (iprocessdata) cxt.getbean ("Demoservice"); @Override public Arguments getdefaultparameters () {//parameter definitions, displayed in the foreground, or undefined Argumentsparams = new Arguments ();
        Params.addargument ("name", "Tom");
        Params.addargument ("Age", "20");
        Params.addargument ("TestName", "setage");
       
    return params; @Override public Sampleresult runtest (Javasamplercontext context) {String testname = context.getpa
        Rameter ("testname");
        Sampleresult sr = new Sampleresult ();
        Super.invokeruntest (testname, Context, SR);
    return SR;
        public void Setage (Javasamplercontext context, Sampleresult SR) {Boolean success = true;
        Sr.setsamplelabel ("Setage");
        Sr.samplestart ();
            try {String age = context.getparameter (' age ');
            String msg = Demoservice.setage (age);
            Thread.Sleep (5000);
            SYSTEM.OUT.PRINTLN (msg);
            Sr.setresponsemessage (msg);
        Sr.setresponsecode ("1000");
        catch (Exception e) {success = false; }finally{SR.SAMpleend ();
        Sr.setsuccessful (Success);
        } public void Sayhi (Javasamplercontext context, Sampleresult SR) {Boolean success = true;
        Sr.setsamplelabel ("Sayhi");
        Sr.samplestart ();
            try {String name = Context.getparameter (' name ');
            String msg = Demoservice.sayhi ("Hi," +name);
            Thread.Sleep (5000);
            SYSTEM.OUT.PRINTLN (msg);
            Sr.setresponsemessage (msg);
        Sr.setresponsecode ("1001");
        catch (Exception e) {success = false;
            }finally{Sr.sampleend ();
        Sr.setsuccessful (Success);
    } @Override public void Teardowntest (Javasamplercontext context) {super.teardowntest (context); }


}

Here we have added a parameter testname, which determines which use case method to call specifically. In this way, we realize that in the same class to write different test cases, feel more elegant, haha. two. Create Java Sampler Test plan in JMeter

To perform the test cases written above in JMeter, there are several steps to follow:

1. The project into a jar package, Method 1 with Eclipse or myeclipse export directly exported jar package, Method 2 with MAVEN package or this install instructions packaging, it is recommended to use MAVEN to manage the project, packaging convenient and not error, I tried to export the jar package directly from the IDE, but I did not find the spring bean configuration file in the execution process, and it didn't happen with maven packaging.

2. Put the jar pack into the JMeter lib/ext path, run JMeter, and find the test case class that you wrote in the new Java request sampler.

3. Copy all the jar packages that the project relies on to the JMeter Lib path, because running your own test cases may use the classes in these jars, or you will not be able to find class during execution. If it is a MAVEN project, you can export all the dependent jars in the project to the Target/dependency folder of the project by executing instructions MVN dependency:copy-dependencies, and then copy to the JMeter lib.

4. Run JMeter start creating your test plan according to specific performance metrics and scenarios.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.