May 22, 2013

JMeter for testing RESTFul web services by posting JSON data and how to use BeanShell

We looked at JMeter tutorial with detailed steps in an earlier tutorial. This is a brief extension to cover JSON post. Now a days, a single page interactive web sites are very popular, and they post JSON based data back to the server to create a new record or to update an existing record.

Step 1: Firstly, you need to set up the header "Content-Type" to "application/json" as shown below.

Step 2: Specify the URL path and paste the relevant JSON data that gets posted as shown below.
 Also, make sure that the HTTP verb used ia a "POST".

Now, there will be scenarios where posting a static JSON data is not good enough, and you will require to manipulate the JSON data. Here are steps to acheve this with

BeanShell Sampler and BeanShell PostProcessor to manipulate JSON data within JMeter

Step 1: Download a Java based JSON library jar to encode and decode JSON data. In this example, I am using the json-simple library that can be downloaded from code-google.

Step 2: Copy the downloaded jar file "json-simple-x.x.x.jar" to JMeter lib folder C:\myapps\apache-jmeter-2.9\lib.

Step 3: Restart the JMeter. Add a Bean Shell Sampler by right clicking and then selecting Add --> Sampler --> Bean Shell Sampler.

To the Bean Shell sampler add a sample static JSON data as shown below, which we would manipulate in the next step.

String dummyJSON =" {\"id\":7787}";

Step 4: Now, add Bean Shell Processor as a child as shown above in the diagram, and the code will use the library we added in step 1.

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

String jsonString = prev.getResponseDataAsString();

//decode string to json object
JSONObject jsonObj = JSONValue.parse(jsonString);

//add another object
jsonObj.put("name","Peter") ;

//encode and put it into jmeter variables with a variable name "jsonResponse"
vars.put("jsonResponse", jsonObj.toString());

Step 5: Finally, in the HTTP sampler, use the variable "jsonResponse", which has the dynamically created (or modified) jsonResponse as a variable. For example: ${jsonResponse}.

That's all to it. It has not only demonstrated how to manipulate JSON data, but also how to use Bean Shell to add coding power and flexibility to JMeter.

Labels: , ,


Anonymous Anonymous said...

Thanks for great article. In addition I would mention that JMeter also provides JSONPath Extractor and JSONPath Assertion to do correlation (handling dynamic stuff) and making sure that result matches expectations.

And check out How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting and kind of Beanshell cookbook

12:20 AM, May 22, 2014  
Blogger Arulkumaran Kumaraswamipillai said...

Thanks for the info glinius.

2:06 PM, May 22, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home