November 4, 2020

Using Beanshell for Beginners

Open Source Automation

JMeter has rich built-in plugins for most things you need. But you could still get stuck while writing complex tests for something specific. In such cases, it’s worth using the Beanshell sampler. It’s really powerful...if you know how to use it. If you’re a Java developer you can easily invoke Java code in Beanshell. However, if you’re not familiar with Java, you might find it difficult to write a Beanshell script. So, in this article I’m going to show you how to write Beanshell scripts without any Java knowledge to achieve open source automation.

Back to top

Beanshell for Beginners: No Java Knowledge Required

For starters: add "Thread group" and Beanshell sampler. The Beanshell sampler has pre-defined variables which you can use in the script, these are: SampleResult, ResponseCode, ResponseMessage, isSuccess, Label, FileName, ctx, vars, props, and log.    

 

JMeter by default supports Beanshell so you can write and run Beanshell scripts in the Beanshell sampler. However, if you want to run them separately you can install the Beanshell console.

 

Type the following in the console:

 

sudo apt-get install bsh

 

Now type "bsh" in the console and you’ll see a prompt message from the Beanshell console. To learn the syntax of Beanshell, try checking out the online tutorial: “Beanshell Quick Start”.

 

Note that I’m not using the Beanshell console for coding. All scripts will be written in the JMeter Beanshell samplers.

Back to top

Coding Your Beanshell Script

Now we can start the step-by-step coding of the Beanshell script. Here are the steps you should take:

 

1. Open the Beanshell sampler and type the following:

 

print("Hello");

 

 

 

 

2. After you’ve run the test, nothing will happen in JMeter.

 

However, if you check the console, i.e STDOUT, where JMeter was launched, you’ll see the text: "Hello". Now clear the Beanshell sampler field and write the following

 

log.info("Hello");

 

3. Before running your test open "Log Viewer" from the "Options" menu.

 

Once you’ve done this, you can run the test. If you check your log, you’ll see the following line:

 

2014/08/25 13:07:19 INFO  - jmeter.util.BeanShellTestElement: Hello

 

This is the result of a previous command.

 

4. Work with JMeter API.

 

Now we know how to print out the text - but this isn’t enough to start writing a Beanshell script. We need to try to learn the JMeter API and how to work with it. You can find documentation about the JMeter API from Apache JMeter.

 

Let’s say we want to send a HTTP request and print out request properties. You should add the “HTTP Request” sampler, “View Results Tree” listener and the “BeanShell PostProcessor” as a sub element of the “HTTP Request”.  

 

 

We use the ctx variable to get access to samplers and their results. The ctx variable stands for JMeterContext class, and to use it we need to know its list of methods. Search for “JMeterContext”  in the JMeter API and open it. In the table “Method Summary”, you’ll see all available methods in JMeterContext (ctx) displayed. We need getCurrentSampler() - which gives access to our “HTTP Request” sampler. If we write a script, it will look like this:

 

print(ctx.getCurrentSampler());

 

5. Save your test and run. In the console, you’ll see the sampler’s full URL.

 

    

 

If you want to print something to STDOUT or log, I recommend adding .toString() at the end of line. So previous line will look like this:

 

print(ctx.getCurrentSampler().toString());

 

In the script, the ctx is JMeterContext class and getCurrentSampler() is it’s method. You can use other methods and see what results you’ll get.

 

 

6. We’ve now printed the thread number and name - but what if we want to get cookies from Beanshell?

 

In such as case, add “HTTP Cookie Manager” as a sub element of the “HTTP Request” sampler. In “HTTP Cookie Manager” add some cookies.

 

Now we need to find the interface of getCurrentSampler(). For this, click “getCurrentSampler()” which redirects to Sampler interface. In the Sampler interface, you’ll need to select the necessary sampler class from “All Known Implementing Classes”. In our case it’s the “HTTPSamplerProxy” class. In “HTTPSamplerProxy”, you’ll need to find the method with the name which includes cookies - which is: getCookieManager(). Open “CookieManager” to see the list of available methods. We need the get() method to print out the sending cookie. Now we can edit the Beanshell script and run the test. After getCurrentSampler(), add method getCookieManager(), get() and define the index 0 for the get() method.  

 

print(ctx.getCurrentSampler().getCookieManager().get(0).toString());

 

7. Save the test and run it. In the console, you’ll see the sending cookie.

 

 

 

 

This command prints only one cookie - but how can we print all the cookies? To solve this problem, we first need to get a count of the cookies. To do this, we can use the following command:

 

print(ctx.getCurrentSampler().getCookieManager().getCookieCount().toString());

 

This will print count of cookies. Now try to add more than two cookies in “HTTP Cookie Manager”.

 

 

 

 

8. In the “BeanShell PostProcessor”, add these lines:

 

cookieCount = ctx.getCurrentSampler().getCookieManager().getCookieCount();

 

for(int i=0; i

   cookie = ctx.getCurrentSampler().getCookieManager().get(i);

   print(cookie);

}

 

Once this has run, it will display all the cookies:

 

 

With the same command, you can also print request headers:

 

print(ctx.getCurrentSampler().getHeaderManager().get(0).toString());

 

However, you’ll need to add the “HTTP Header Manager” config element and some headers.

 

9. Send properties with the Beanshell sampler

 

We’ve already described how to read properties with the Beanshell sampler. Now we need to learn how to send them. Let’s say that you need to retrieve data from the website and send it as the maximum number of elements in the cache config. If you don’t know how to retrieve specific information, you can find out in this post: “Using Regular Expressions in JMeter”. However, this isn’t mandatory as you can define variables without parsing response data. Let’s say we have a value which is stored in a variable and should be sent with Beanshell. To define the variable “maxCache”, add “jp@gc - Parameterized Controller” into the thread group and set any number.

 

 

 

 

 

To send data with Beanshell, you’ll need to use the “BeanShell PreProcessor” - not the “BeanShell PostProcessor”. So add “BeanShell PreProcessor” as a sub element to the “HTTP Request” sampler and insert the following code:

 

max = vars.get("maxCache");

int max = Integer.parseInt(max);

ctx.getCurrentSampler().getCacheManager().setMaxSize(max);

 

 

 

 

10. Analyze the Beanshell script:

 

The first line max = vars.get("maxCache"); gets the maxCache value and re-assigns it to the max variable.

 

The second line, int max = Integer.parseInt(max); changes the type of variable from “String” to “Int” as the method public void setMaxSize(int size) only accepts integer.

 

The third line comes from the JMeter API; setMaxSize() is the method in CacheManager class.

Back to top

 

11. In “Beanshell PostProcessor”, insert this script:

 

print(ctx.getCurrentSampler().getCacheManager().getMaxSize().toString());

 

Now run the test. After running the test,  you’ll see the maxCache value in the console. You should be able to see that it was assigned in “jp@gc - Parameterized Controller”. The “BeanShell PreProcessor” overrides the max cache elements value,  which is also defined in “HTTP Cache Manager”.   

 

12. Find the necessary class from the JMeter API

 

You can search for the name of the class in the JMeter API - but what if you can’t find the class of element in the test tree?

 

In such a case, you should first of all open up the “Log Viewer”. To find the class name of an element, you’ll need to select it and click “What’s this node?” from the “Help” menu or press Ctrl+W. In “Log viewer”, you will be able to see the class name:

 

 

 

13. Now add the “Beanshell” sampler and this line:

 

javap(org.apache.jmeter.reporters.ResultCollector);

 

Afterwards, save and run the test. If you open the console, you’ll be able to see a list of available methods:

 

 

The javap() command prints the public fields and methods of the specified class. This way might be much easier than searching for the class in the JMeter API website.  

 

14. Import the classes


We’ve been using classes without importing them, as most have already been imported when you launch JMeter. However, this doesn’t mean that never need to import them. To avoid problems when running Beanshell scripts, I recommend always importing classes which you’re using. To import a class you’ll need to add the line

 

import domain_name.package_name.class_name;


 

For example:

 

import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;

import org.apache.jmeter.protocol.http.control.CookieManager;

import org.apache.jmeter.protocol.http.control.CacheManager;

 

Most of time you don’t need a GUI package, so you shouldn’t import them, for example the GUI package of CacheManager org.apache.jmeter.protocol.http.gui.CacheManagerGui.

 

15. Debug the Beanshell script

 

Finally, you might need to debug the script. You can learn the basics of debugging a JMeter script in this blog post: “How to debug your Apache JMeter script”.

 

If you want to debug your Beanshell script, you can with debug() command which will verbosely print debug info. To use it, just add debug(); on the first line of your script. After running the test, you’ll be able to see debugging information when you open the console.

Learn more about JMeter at BlazeMeter University

START TESTING NOW

 

Related Resources: 

Back to top