Jmeter generates json request payload dynamically
I have a Jmeter test plan where I want my HttpSampler to send a post request.
The request body should contain Json like this:
{
"productIds" : [
"p1",
"p2",
...
]
}
I have a random variable generator that returns a well-formed product with every call. What I would like to do is generate the payload by populating the productIds with a random pid taken from the generator directly in the request body. Something like (assume *** is a scripting escape):
{
"productIds" : [
***
for i in (1, $productsCount) {
write("\"$randomPid\"\n")
}
***
]
}
Is it possible? If so, how? If not, how do you approach the problem?
Thank!
+3
source to share
1 answer
- Add Beanshell PreProcessor as a child of the request you want to parameterize
-
Place the following code in the PreProcessor "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());
- Place the value $ {productsCount} in the "Parameters" line
- Refer to the resulting payload as
${json}
where required
See How to Use BeanShell: A Favorite Built-in JMeter Component for more information on Apache JMeter Beanshell Scripting.
+8
source to share