Using a Custom Jar in BeanShell Sampler in Jmeter
Let us see an example on how we can use a custom Java classes and methods in JMeter BeanShell sampler.
Outline of the steps:
- Write Java classes and methods in IDE tools like Eclipse or NetBeans
- Create a Jar of the above project
- Import the Jar to JMeter location
- Use the Java method in Jmeter BeanShell sampler
- Run the test plan and check results
Let us see the above step by step:
For getting the concepts clear, let us create an example class which will generate factorial of a given number. The number will also be a random number.
- Let us create a class containing the method to calculate a factorial and this will be used in JMeter. I created the method as below in eclipse.
Here we have created new project “FactorialJar”. Under the project, we created two projects named as “FactClass” and “TestFact”. Under each class we created a Class called “Fact” and “Facttest”.
Code for Fact.java is as below:
package FactClass;
public class Fact {
public int facto(int f)
{
int fact=1;
for(int i=1;i<=f;i++)
fact=fact*i;
return fact;
}
}
Code for Facttest.java is as below:
package TestFact;
import FactClass.Fact;
public class Facttest {
public static void main(String[] args) {
Fact fac = new Fact();
int res=fac.facto(4);
System.out.println("Factorial =" + res);
}
}
Once completed, run the project and verify the code is working as expected. The Factorial for 4 should be displayed. The output will be as below in Eclipse:
Factorial =24
- Create a Jar of the above project
To create a JAR from the project, right click on the project and select Export… and choose JAR file option under Java drop down.
Click on Next and select the JAR file location and name the jar as “Facto.jar”. Click on Finish.
The “Facto.jar” will be created at the above mentioned location.
- Import the Jar to JMeter location
Copy the JAR from the JAR location mentioned above.
Paste the JAR into Jmeter Path : <JMeter Path>/lib/ext folder.
Relaunch the JMeter GUI
- Use the Java method in Jmeter BeanShell sampler
Let us create a TestPlan as shown below:
Random Variable is defined as below:
The BeanShell sampler code is as below:
import FactClass.Fact;
Fact fac = new Fact();
int result=fac.facto(Integer.parseInt(vars.get("num")));
vars.put("result",result.toString());
print("Factorial of " + vars.get("num") + " = " + vars.get("result"));
log.info("Factorial of " + vars.get("num") + " = " + vars.get("result"));
- Run the test plan and check results
Run the test plan and it will generate the factorial of a random number between 1-10.
The output is as below:
We have the output in the Log Viewer and Console as below
Hi thank you for your information, I need to execute external jar file with with multiple parameters ie.,
ReplyDeletejava -jar c:/abc.jar kuslsele.c.com sdf user pwd
How can i execute this command line argument in jmeter