Documenting Problems That Were Difficult To Find The Answer To

Creating a Java Sampler for JMeter

This was written while using JMeter versions 2.7 and 2.8. This article was written due to the difficulty I initially found in creating a Java Sampler for JMeter.

A Java Sampler is an easy way of creating a JMeter test by using native Java code. In fact there are several approaches that can be taken when creating a JMeter Sampler using Java code – they include:

  • BeanShell Samplerpros: very quick and dirty, no need to create your own class or compile anything, cons: very limited in power and flexibility
  • JUnit Samplerpros: can specify multiple test types inside one class, cons: cannot provide variables to test from JMeter script
  • Java Samplerpros: can specify JMeter script variables to class, cons: cannot have more than one test in a class

JUnit Sampler

A JUnit Sampler can be quickly constructed using the following as a template:

package com.wordpress.newspaint.jmeter.junit.demo;

import junit.framework.TestCase;

// test methods MUST BEING WITH THE PREFIX "test"
public class ExampleJUnitTestClass extends TestCase {
    float first = (float)2.0;
    float second = (float)20.0;

    public void testaddition() {
        assertTrue( "Addition Greater Than", ( ( first + second ) > 21.99 ) );
        assertTrue( "Addition Less Than", ( ( first + second ) < 22.01 ) );

    public void testmulti() {
        assertTrue( "Multiplication Greater Than", ( ( first * second ) > 39.99 ) );
        assertTrue( "Multiplication Less Than", ( ( first * second ) < 40.01 ) );

This can be compiled and the resulting jar placed in the lib/junit subdirectory of the JMeter distribution.

Tests are very simple and apart from duration and pass/fail results there is little more that can be gained using this method.

Java Sampler

The Java Sampler is a powerful means of testing just about anything. The big advantages are that variables can be taken from the JMeter script (such as thread number, or user name, or whatever you want) and that results can contain a specific error code as well as custom messages and data – more importantly you can control when the timer for the test starts and finishes.

The following can be an example Java Sampler class:


import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.samplers.SampleResult;

public class ExampleJavaTestClass extends AbstractJavaSamplerClient implements Serializable {
    private static final long serialVersionUID = 1L;

    // set up default arguments for the JMeter GUI
    public Arguments getDefaultParameters() {
        Arguments defaultParameters = new Arguments();
        defaultParameters.addArgument("URL", "");
        defaultParameters.addArgument("SEARCHFOR", "newspaint");
        return defaultParameters;

    public SampleResult runTest(JavaSamplerContext context) {
        // pull parameters
        String urlString = context.getParameter( "URL" );
        String searchFor = context.getParameter( "SEARCHFOR" );
        SampleResult result = new SampleResult();
        result.sampleStart(); // start stopwatch
        try {
   url = new + "?q=" + searchFor);
   connection = (
            )url.openConnection(); // have to cast connection

            result.sampleEnd(); // stop stopwatch
            result.setSuccessful( true );
            result.setResponseMessage( "Successfully performed action" );
            result.setResponseCodeOK(); // 200 code
        } catch (Exception e) {
            result.sampleEnd(); // stop stopwatch
            result.setSuccessful( false );
            result.setResponseMessage( "Exception: " + e );

            // get stack trace as a String to return as document data
   stringWriter = new;
            e.printStackTrace( new stringWriter ) );
            result.setResponseData( stringWriter.toString() );
            result.setDataType( org.apache.jmeter.samplers.SampleResult.TEXT );
            result.setResponseCode( "500" );

        return result;

This can be compiled and the resulting jar placed in the lib/ext subdirectory of the JMeter distribution.

The ability to set variables can be seen from this resulting Sampler screenshot in JMeter:

Java Sampler Demo Showing Variable Input

Java Sampler Demo Showing Variable Input

Those variables can be set to anything – including dynamic variables such as “${__threadNum}”.

The advantage of setting response data is that it will be displayed in the “View Results Tree” listener’s “Response Data” tab – so I find putting the stack trace of any exceptions in there very useful to assist in debugging my tests. Such an example is shown in the next screen shot when attempting to provide an invalid domain name to the above example:

Stack Trace Displayed in Request Data Tab in Results Tree


I found I needed the following jars to compile this class:

  • ApacheJMeter_core.jar
  • ApacheJMeter_java.jar

Persistent Variables in a Thread

Maybe you want to create several steps/tests. So you create several classes. But how do you share information between tests? Let’s say your first test returned a certain string you wanted to use as the basis for your second test.

JMeter allows you to store variables in the current Thread’s context – so each thread would have its own context.

import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
// store a value
JMeterVariables vars = JMeterContextService.getContext().getVariables();
vars.putObject( "mySpecialValue", "" );
JMeterContextService.getContext().setVariables( vars );
// fetch a value
JMeterVariables vars = JMeterContextService.getContext().getVariables();
String mySpecialValue = (String)vars.getObject( "mySpecialValue" );
// delete a value
JMeterVariables vars = JMeterContextService.getContext().getVariables();
vars.remove( "mySpecialValue" );
JMeterContextService.getContext().setVariables( vars );

Note that you can store anything including classes. But if your thread loops the value will persist – so you must explicitly remove it but setting the value to null if you don’t want to use it any more. Overwriting a value will cause the existing to be freed/destroyed.

You can also use the variables you set in other samplers – such as the HTTP Sampler! If you store a String in, say, “mySpecialValue” then you can refer to it in your other samplers using the JMeter variable notation (in this case ${mySpecialValue}).

BeanShell Interpreter

This is a quick-and-dirty means of adding Java code to your JMeter scripts. But best to read JMeter best practices first.

There is another post about the BeanShell Interpreter at this link.

5 responses to “Creating a Java Sampler for JMeter

  1. ravi December 16, 2014 at 3:36 am

    This article was useful for me. Thank you for sharing this.

  2. Boris July 15, 2015 at 2:54 pm

    I add jar to lib/ext, but it not visible in Java Request – Classname drop down. Do I need to make additional steps?

  3. GR February 12, 2016 at 8:05 pm

    Thanks for this post. It was very informative and helpful.

  4. Oliver Weise January 4, 2017 at 2:42 pm

    Thanks. This saved me loads of time!

  5. Marco April 24, 2017 at 8:17 pm

    Thanks for the post, it was really helpful. Do you know if there’s a way to reference the class under test dependencies instead of copying them to the JMeter lib folder?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: