我需要每次创建一个随机的正整数并将其发送到Ga特林中的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 约定:在生成新值时命名为驼峰命名法 (camelCase),(),最后没有
;
。
要使用准备好的方法,您不能使用加特林 EL 字符串。语法非常有限,基本上
"${OrderRef}"
在 Ga特林会话中搜索名称为 OrderRef
的变量。
正确的方法是使用表达式函数为:
.exec(
http("OrderCreation")
.post("/abc/orders")
.body(StringBody(session => s"""{ "orderReference": "${orderRef()}" }""")).asJSON
)
在这里,您正在创建匿名函数,以 Gattle
Session
并返回 String
作为主体。字符串通过标准 Scala 字符串插值机制组成,并使用之前准备好的函数orderRef()
。
当然你可以省略 Scala 字符串插值:
.body(StringBody(session => "{ \"orderReference\": " + orderRef() +" }" )).asJSON
使用 Scala 时,这不是很受欢迎的风格。
请参阅 Gattle 文档中的 Request Body 并阅读有关 Galting EL 语法的更多详细信息。
另一种方法是定义 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
)
这里的情况有所不同,首先我们定义 feeder,然后将其附加到会话,然后通过 Gadling EL string 在请求正文中使用它的值。当加特林在附加到每个虚拟用户的会话之前从馈送器获取馈送器值时,此方法有效。了解更多有关喂食器的信息这里。
建议:如果您的场景很简单,请从第一个解决方案开始。如果需要更复杂,请考虑喂食器。
享受
import scala.concurrent.duration._
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import io.gatling.jdbc.Predef._
class PostRq extends Simulation {
val httpProtocol = http.baseUrl("http://127.0.0.1:8080")
.contentTypeHeader("application/json")
val csvFeeder = csv("user-files/simulations/your_path/your.csv").random
val scn = scenario("Request")
.feed(csvFeeder)
.exec(
http("Request endpoint with dynamic payload")
.post("/your_endpoint")
.body(ElFileBody("user-files/simulations/your_path/template.json"))
)
setUp(
scn.inject(
constantUsersPerSec(5) during (1 seconds),
nothingFor(4 second),
constantUsersPerSec(10) during (1 seconds),
nothingFor(4 second)
)
).protocols(httpProtocol)
}
在 JSON 模板变量中定义如下
“key_1”:“#{my_var_1}”,“key_2”:“#{my_var_2}”
。 在 CSV 数据集中,列名称必须与变量名称匹配。
my_var_1,my_var_2
value,value
value,value
...