<img height="1" width="1" style="display:none;" alt="" src="https://dc.ads.linkedin.com/collect/?pid=1005900&amp;fmt=gif">

Insights

Using the power of Java programming in your JMeter scripts (BeanShell)

When creating a script in JMeter, you may have instances where you need to perform manipulation on variables or arrays you’ve captured using a Regular Expression Extractor or XPath Extractor. This is where BeanShell can come in handy.

What is BeanShell?

BeanShell is a scripting language which allows you to tap into the power of the Java programming language in order to perform manipulation on your Jmeter variables.

The general steps to achieving this are:

  • create a BeanShell Listener after your RegularExpression/XPath extractor object
  • get your variable into the BeanShell Listener by using ‘vars.get(“NameofVariable”)
  • perform processing
  • put your processed variable(s) back into the specified Jmeter variable

Let’s take a look at an example. Assume you have captured values in a JMeter array containing “10,6,5,8” and you wanted to manually add another element to get “10,6,5,8,12”, your BeanShell Listener would contain the following:


// first we get the number of elements our Jmeter array contains
int count = Integer.parseInt(vars.get("JMeterArr_matchNr"));
String comma = "%2C"; // %2C is the ASCII code for a comma
// create a new string buffer object which will
// store our generated data
StringBuffer sb = new StringBuffer();
// loop through the Jmeter array
for(int i=1;i<=count;i++)
{

// append each Jmeter array element to the string buffer
sb.append(vars.get("dayValueX_" + i));
sb.append(comma); // append a comma after each element

}
// by this time the loop will have finished and now we can
// simply add our own element to our generated string
sb.append("12");
// put our string buffer contents back into a JMeter variable
// called ‘outputString’
vars.put("outputString",sb.toString());
// ${outputString} contains ‘10%2C6%2C5%2C8%2C12’

Of course this is a very simple example but demonstrates manipulating Jmeter variables using BeanShell. This could be extended to manipulate more than one variable, substituting the value of a particular variable for another etc. As well as manipulating your JMeter variables, you could also use a BeanShell Sampler to test for conditions such as whether your JMeter variable is holding an expected value. If not, you could flag up an error message which in turn terminates your script.

Conclusion

Overall, BeanShell can be useful when performing tasks which JMeter might not directly support. It is a lightweight Java scripting language and is definitely worth spending time looking into if you use Jmeter on a regular basis.

To learn more about the benefits of performance testing and the secrets of its delivery – download our ebook here.

Download the Performance Testing Primer