I have a Jmeter test plan where I want my HttpSampler to send a post request.
The body of the request should contain Json as follows:
{
"productIds" : [
"p1",
"p2",
...
]
}
I have setup a random variable generator that returns well-formed productId with every call. What I would like to do is generating the payload by filling productIds of random pid's taken from the generator, directly in the body of the request. Something like (suppose *** is the scripting escape):
{
"productIds" : [
***
for i in (1, $productsCount) {
write("\"$randomPid\"\n")
}
***
]
}
Is it possible? If yes, how? If not, how would you approach the issue?
Thanks!
To perform sending the JSON payload we need a different configuration. First, we need to add HTTP Header Manager into our HTTP Request in order to set Content-Type as application/json. We then put the JSON payload into the Body Data section of our HTTP Request Sampler.
Put following code into the PreProcessor's "Script" area:
StringBuilder result = new StringBuilder();
String newline = System.getProperty("line.separator");
int max = Integer.parseInt(Parameters);
Random random = new Random();
result.append("{");
result.append("\"productIds\" : [");
result.append(newline);
for (int i = 1; i < max; i++) {
result.append("\"").append(random.nextInt()).append("\",");
result.append(newline);
}
result.append("]");
result.append(newline);
result.append("}");
vars.put("json", result.toString());
${json}
where requiredSee How to use BeanShell: JMeter's favorite built-in component guide for more details on Beanshell scripting in Apache JMeter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With