How to add random value in Json Body in Gatling?

房东的猫 提交于 2019-12-03 10:57:11
Teliatko

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!