
When developing tests, it is often necessary to write code in the tests themselves. This code might be long, it might be repeated in several tests, or might be written only for a specific test. Also, the code written in the tests might have to change or be supplemented if the requirements change.
This can take a long time and is prone for errors. Suppose that we have 20 Apache JMeter™ tests in which the same code is written and at some point in time we decide to make changes to this code for all 20 tests. Changes must be made in each test. To get rid of such routine work, we can call codes to tests from a JAR file (JAR file is Java Archive).
The code that will be used in the tests that describes the test methods is written in the development environment (for example, IntelliJ IDEA ,Eclipse) only once, a JAR file is created and only the call of the required code and the test request is performed in the tests themselves. We do not need to write the code directly in the test, and if for some reason we need to change the code, we change it only in one place.
Prerequisites
1. Download and install Eclipse or you can use any IDE like intellij etc.
2.Create a project in Eclipse and write Java Classes and methods.For Example ,below code parse an URL and fetch the details like protocol ,port number and host name etc.

3.Test the above code in Eclipse and Create a Jar file. Right click the project and select the option Export..

4.Select the JAR file option from Export window.

5. Select the desired Java class file and provide the JAR file name.

6. Click finish , a JAR file would be created.
7.Launch the JMeter and add a thread group and bean shell sampler.

8. Add this JAR file to Jmeter Test plan under Library section

9.Add the below code into bean shell sampler to import the class and methods.
import qautomation.blog.test.Commonfunctions;
try{
Commonfunctions classObj = new Commonfunctions();
String hostName = classObj.getHostName("http://restapi.demoqa.com");
int portNumber = classObj.getPortNumber("http://restapi.demoqa.com");
if(portNumber<0)
portNumber = 0;
String protocol = classObj.getProtocol("http://restapi.demoqa.com");
log.info("***************Host Name = "+hostName);
log.info("*************Port Number = "+String.valueOf(portNumber));
log.info("****************Protocol = "+protocol);
}
catch (Throwable ex) {
log.error("ERROR: ", ex);
throw ex;
}

10. Run the code from run button and see the Log for result.

Reference:
https://www.linkedin.com/pulse/using-custom-jar-beanshell-sampler-jmeter-lakshmi-narayan
https://wiki.workassis.com/how-to-add-external-packagesjar-in-to-jmeter/
Categories: Uncategorized
1 reply »