Even though general functionalities of JMeter cover many needs of a performance test, you might need additional scripting. Apache JMeter has the functionality to run Java code snippets during your test execution. BeanShell has access to internal JMeter features and any library located in your JMeter lib folder.
When using BeanShell, you can use “vars” variable to get and set values generated in the test context. This post will cover those functionalities.
BeanShell vars.get() usage
Create a sampler to request a product in amazon.com website.
Then add a Post CSS/JQuery Extractor and extract the buying price. Whenever this request is executed, JMeter will create a variable on memory with the “Reference Name”. This variable is only available during that test. When the execution is finished, it will be erased from memory.
Then add a BeanShell Post Processor to your sampler as a child element. Add the code below.
String price = vars.get("price");
log.info(“Buying Price Value is “+price);
if(price == 0)
log.info(“Error in prices”);
log.info(“Price is in valid range”);
vars.get(“price”) will get the value extracted by CSS/JQuery Extractor and assign it to a String variable.
Then we do some stuff with the price value. That part is pure Java code. You can do anything you want.
When you execute the test, log.info() will create logs in your Log Viewer Panel.
BeanShell vars.put() usage
You can set variables in your context during your test execution. This can be achieved by using vars.put(“KEY”, “VALUE”) method. Suppose that you have a scenario where you have to create users in a system. Every user needs a unique e-mail address and password. You want to create passwords and emails during a test run.
We have a HTTP sampler with POST methods. We need to pass some parameters to it and define some variables in the panel. Those variables will be created by BeanShell Processor.
Add Pre BeanShell Processor as a child to it. Add the code below.
String uuid = UUID.randomUUID().toString();
String tokenizedUUID = uuid.split(“-“);
String Email = tokenizedUUID+”@loadium.com”;
log.info(“New User Mail “+Email);
log.info(“New User Password “+tokenizedUUID);
The code generates a UUID string. We split that UUID with String class’ split function. We do some manipulation and put two values in test context by using vars.put(“KEY”, “VALUE”) function. Now we create email, password variable on the fly.
Now run your test and take a look at the Tree View Listener. Your post data are like below. Emails and passwords are unique to each request.
In case you are stuck somewhere during your performance test design, BeanShell Processor will save your day. As a result, it will be your most favorite JMeter component ever.
Note: In case you need additional operations, like CRUD operations to a data source, that JMeter is not able to handle with predefined libraries, just add necessary jar files in the lib folder in JMeter’s installation folder and use them in the BeanShell Processor.