You can script using multiple languages within Jmeter. Beanshell and Groovy both run lightning quick and are 99% (or thereabouts) compatible with standard java syntax. Both languages can be utilized inside the JSR223 Post Processor.
In this tutorial series I will demonstrate some tips and tricks that will help you manipulate data for API testing with Jmeter. I am assuming that you are already somewhat familiar with Jmeter and Java.
First create a new Jmeter script and add a UDV to intialize the variables.
${Server} = This is the main URL of the web service
${Protocol} = Communications protocol
Setup the Test Plan in Jmeter as follows:
- Create a Thread Group.
- Create an HTTP Request.
- Select GET in the Method dropdown.
- Add an HTTP Header Manager to the HTTP request.
- Add three JSON Path Post Processors to the HTTP request.
- Add a JSR223 Post Processor to the HTTP request.
When finished, you node tree should look something like this:
The response is expected to be in JSON format, so the Content-Type and Accept should both be set to “application/json”. Configure the Header Manager as follows:
We are going to run a GET request against the public Star Wars API.
The GET request should look like this (Body Data is blank in this request):
Use the JSON Path Post Processors to easily scrub the response for specific values:
Inside the JSR223 Post Processor under the GET request, select Beanshell in the programming language dropdown and paste the following code in the script box:
//get extracted values from vars created in JSONPath Post Processors String extName = vars.get("name"); String extBirth = vars.get("birthyear"); String extHome = vars.get("homeworld"); //get response from prev sampler String getResponse = prev.getResponseDataAsString(); //print response data to log log.info("\n" + "Extracted name => " + extName + "\n" + "Extracted birthyear => " + extBirth + "\n" + "Extracted homeworld => " + extHome + "\n" + "Entire GET Response is:" + "\n" + getResponse + "\n");
This should print the following to the log viewer:
To see the entire reponse in JSON format, add a View Result Tree listener to your test and select JSON next to the Response Data tab.
What did we do here ?
- We used the built-in JSON-Path extractors to do the dirty work and get three specific values that we need from the response. This can also be accomplished by writing code inside a JSR223 Post Processor. Instead we used built-in extractors, so there was no need to import any libraries or write any extra code.
- We used Correlation to store extracted values in variables that can be accessed at any point inside the thread.
- We passed the extracted values into the JSR223 Post Processor and printed them inside the log viewer. These values could just as easily be written to a text log file or a CSV output file.
- We used the prev variable to get the entire JSON response as a string.