如何在Gatling中的Json正文中添加随机值?

如何在Gatling中的Json正文中添加随机值?,json,gatling,Json,Gatling,我每次需要创建一个随机的正整数,并将其发送到Gatling中的Json主体 我使用以下代码创建了一个随机的正整数: val r = new scala.util.Random; val OrderRef = r.nextInt(Integer.MAX_VALUE); 但是,如何将随机生成的值输入json主体 我试过: .exec(http("OrderCreation") .post("/abc/orders") .body(StringBody("""{ "orderReferenc

我每次需要创建一个随机的正整数,并将其发送到Gatling中的Json主体

我使用以下代码创建了一个随机的正整数:

val  r = new scala.util.Random;
val OrderRef = r.nextInt(Integer.MAX_VALUE);
但是,如何将随机生成的值输入json主体

我试过:

.exec(http("OrderCreation")
.post("/abc/orders")
.body(StringBody("""{    "orderReference": "${OrderRef}"}""").asJson)  
但是,这似乎不起作用。有什么线索吗


谢谢

首先,每次都要生成随机数,因此,
OrderRef
必须是一种方法,如:

def orderRef() = Random.nextInt(Integer.MAX_VALUE)
旁注:按Scala约定:name camelCase,()生成新值时,不使用
最后

要使用准备好的方法,不能使用Gatling EL字符串。语法非常有限,基本上
“${OrderRef}”
在Gatling会话中搜索名为
OrderRef
的变量

正确的方法是将表达式函数用作:

在这里,您将以Gatling
Session
并返回
String
作为主体来创建匿名函数。字符串通过标准Scala字符串插值机制组成,并使用before prepared函数
orderRef()

当然,您可以省略Scala字符串插值,如下所示:

.body(StringBody(session => "{ \"orderReference\": " + orderRef() +" }" )).asJSON
在使用Scala时,这不是非常首选的样式

请参阅Gatling文档中的更多详细信息,并阅读更多信息

另一种方法是定义馈线:

// 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
  )
这里的情况不同,首先定义feeder,然后将其附加到会话,然后通过gatlingel字符串在请求体中使用其值。在每个虚拟用户的连接到会话之前,Gatling从feeder获取feeder值时,这一点起作用。请参阅有关馈线的更多信息

建议:如果您的场景很简单,请从第一个解决方案开始。如果需要更复杂的时间,请考虑馈线


享受吧

第一个“正确”的方法对我不起作用。另一种方法确实有效。谢谢。这两种选择对我都不起作用@Teliatko您使用的是什么版本的gatling?请注意,第一个选项实际上对我有效,但第二个选项对我无效。@VivekRao,当时我正在使用gatling 2.2。你的版本是什么?我想更新新版本的答案。有一个变化。
// 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
  )