Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add random value in Json Body in Gatling?

Tags:

I need to create a random positive integer each time and send it to Json body in Gatling.

I used the below code to create a random positive ineger:

val  r = new scala.util.Random; val OrderRef = r.nextInt(Integer.MAX_VALUE); 

but, How can I feed the randomly generated value into the json body?

I tried:

.exec(http("OrderCreation") .post("/abc/orders") .body(StringBody("""{    "orderReference": "${OrderRef}"}""").asJson)   

But, this doesn't seem to work. Any clues please.

Thanks!

like image 291
Gold Meen Avatar asked Mar 07 '16 12:03

Gold Meen


1 Answers

First of all you want to generate random number each time, thus OrderRef has to be a method, like:

def orderRef() = Random.nextInt(Integer.MAX_VALUE) 

Side comment: by Scala convention: name camelCase, () while it generates new values, without ; in the end.

To use the prepared method you cannot use the Gatling EL string. Syntax is very limited and basically "${OrderRef}" searches for variable with name OrderRef in Gatling Session.

Correct way is to use Expression function as:

.exec(    http("OrderCreation")   .post("/abc/orders")   .body(StringBody(session => s"""{ "orderReference": "${orderRef()}" }""")).asJSON ) 

Here you are creating anonymous function taking Gatling Session and returning String as body. String is composed via standard Scala string interpolation mechanism and uses before prepared function orderRef().

Of course you can omit Scala string interpolation as:

.body(StringBody(session => "{ \"orderReference\": " + orderRef() +" }" )).asJSON 

which is not very preferred style when using Scala.

See more details at Gatling documentation to Request Body and read more about Galting EL syntax.

An alternative way is to define a Feeder:

// Define an infinite feeder which calculates random numbers  val orderRefs = Iterator.continually(   // Random number will be accessible in session under variable "OrderRef"   Map("OrderRef" -> Random.nextInt(Integer.MAX_VALUE)) )  val scn = scenario("RandomJsonBody")   .feed(orderRefs) // attaching feeder to session   .exec(      http("OrderCreation")     .post("/abc/orders")     // Accessing variable "OrderRef" from session     .body(StringBody("""{ "orderReference": "${OrderRef}" }""")).asJSON   ) 

Here the situation is different, first we define the feeder, then we attach it to session and then use its value in request body via Gatling EL string. This works while the feeder value is taken from feeder by Gatling before an attached to session for each virtual user. See more about feeders here.

Recommendation: If you scenario is simple, start with first solution. If it takes more complex think about feeders.

Enjoy

like image 104
Teliatko Avatar answered Sep 19 '22 13:09

Teliatko