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 Sampler – pros: very quick and dirty, no need to create your own class or compile anything, cons: very limited in power and flexibility
- JUnit Sampler – pros: can specify multiple test types inside one class, cons: cannot provide variables to test from JMeter script
- Java Sampler – pros: 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:
package com.wordpress.newspaint.jmeter.java.demo;
import java.io.Serializable;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
public class ExampleJavaTestClass extends AbstractJavaSamplerClient implements Serializable {
private static final long serialVersionUID = 1L;
// set up default arguments for the JMeter GUI
@Override
public Arguments getDefaultParameters() {
Arguments defaultParameters = new Arguments();
defaultParameters.addArgument("URL", "http://www.google.com/");
defaultParameters.addArgument("SEARCHFOR", "newspaint");
return defaultParameters;
}
@Override
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 {
java.net.URL url = new java.net.URL(urlString + "?q=" + searchFor);
java.net.HttpURLConnection connection = (
java.net.HttpURLConnection
)url.openConnection(); // have to cast connection
connection.setRequestMethod("GET");
connection.connect();
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
java.io.StringWriter stringWriter = new java.io.StringWriter();
e.printStackTrace( new java.io.PrintWriter( 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
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
Jars
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", "http://www.apache.org/" );
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.
Recent Comments