5
votes

I am using JMeter to send HTTP POST requests.

My body of the request is JSON, for example something like {"Var1": "${Var1}","Var2": ${Var2},"Var3":"${Var3}"}.

These are set in the parameters of the HTTP requests with no name for the parameter. This works fine and I am able to send requests using the variables that I set in a beanshell pre processor (by setting the variables and using vars.put() ).

My question is how can I send programmatically through the preprocessor part of the parameters? For example:

if(a){
send parameters `{"Var1": "${Var1}","Var2": ${Var2}` as my JSON
}
else {
send parameters `{"Var3":"${Var3}"}` as my JSON
}

vars.remove() doesn't work for me as it removes the value from the variable but still sends it in the request (for example as "${Var1}").

3

3 Answers

0
votes

Replace the preprocessor by a Beanshell Sampler that will compute a boolean value a and put it as a var:

vars.put("a", value)

Then use 2 If Controllers where each one will contain a sampler with the different parameters.

Condition of first one will be ${a} and for be it will be the negation of ${a}.

0
votes

Just use the "Body Data" tab. You can conditionally create the JSON string and then just "print" the variable in the body data using normal placeholders.

0
votes

The easiest and fastest way of achieving what you want to do is to use the JMeter if controller (Add -> Logic controller -> If controller).

You add an if controller to the Thread Group that you're working on and place your expression that returns a boolean in Condition (default Javascript). As a child node for the if controller you place the HTTP Request sampler that you want to fire in case the if is successful.

Suppose you want to send a request if a property that you are passing to JMeter exists:

${__P(media)}.length > 0

The you add another if controller with a negated condition for what you just checked with another HTTP Request sampler.

You're done.