This is the second post about load testing with Apache JMeter, read the first post here: A step by step tutorial about load testing relational databases.
JMeter has lots of Samplers. If you need a sampler that is not provided by JMeter you can write your custom sampler. (custom samplers are called "Java Request" in JMeter terminology)
This post will show you, step by step, how to write a JMeter Java Request.
Step 1: Preparing the development environment
Add these two jar files to the java classpath.- $JMETER_HOME/lib/ext/ApacheJMeter_core.jar
- $JMETER_HOME/lib/ext/ApacheJMeter_java.jar
Step 2: Extending AbstractJavaSamplerClient
After setting up the classpath, create a custom sampler by extending AbstractJavaSamplerClient and override the following methods.public Arguments getDefaultParameters() {...} public void setupTest(JavaSamplerContext context) {...} public void teardownTest(JavaSamplerContext context) {...} public SampleResult runTest(JavaSamplerContext context) {...}getDefaultParameters
Implement getDefaultParameters if you want initial values for test paramters. JMeter will display the parameters in its Java Request configuration GUI. (See the contents of the red rectangle in the picture below.) Here's an example implementation:
public Arguments getDefaultParameters() { Arguments defaultParameters = new Arguments(); defaultParameters.addArgument("memcached_servers", "localhost:11211"); defaultParameters.addArgument("username", "testuser"); defaultParameters.addArgument("password", "testpasswd"); return defaultParameters; }setupTest
This is where you read test parameters and initialize your test client. JMeter calls this method only once for each test thread.
teardownTest
Clean up the mess.
runTest
Write your test logic in this method. JMeter will call runTest method for every execution of test threads. Here is a typical runTest implementation:
@Override public SampleResult runTest(JavaSamplerContext context) { SampleResult result = new SampleResult(); boolean success = true; result.sampleStart(); // // Write your test code here. // result.sampleEnd(); result.setSuccessful(success); return result; }The time elapsed betweed result.sampleStart() and result.sampleEnd() is used to calculate average response time of the application under test.
Step 3: Deploy your custom sampler
When you are done create a jar file (containing your custom sampler) in the $JMETER_HOME/lib/ext/ directory. JMeter will display your java request in the java request configuration page.You can see the results of your test by adding listeners to your test plan. "A step by step tutorial about load testing relational databases" post shows how to add listeners to test plans.