我有以下两种方法:
def randomStartMethod() : Long = {
var range = 1000L
var r = ThreadLocalRandom.current().nextLong(10L*range)
var randomStart = 1396024675000L + r
return randomStart
}
def randomStopMethod() : Long = {
var range = 1000L
val r = ThreadLocalRandom.current().nextLong(10L*range)
val randomStop = 1396024675000L + r*2L
return randomStop
}
然后我将它添加到请求体中,如下所示:
val activity = repeat(10, "i") {
exec(http("POST activity post")
.post("/activity/")
.header("Content-Type", "application/json; charset=ISO-8859-1")
.header("accept", "*/*")
.body(StringBody(
s"""
|{
| "id": "activityId",
| "type": "run",
| "start_epoch_ms": "${randomStartMethod()}",
| "end_epoch_ms": "${randomStop()}",
| "metrics": [
| {
| "type": "distance",
| "unit": "KM",
| "source": "nike.running.ios",
| "values": [
| {
| "start_epoch_ms": "${randomStartMethod()}",
| "end_epoch_ms": "${randomStopMethod()}",
| "value": 2.0
| }
|
| ]
| }
| ]
|}
""".stripMargin)).
asJSON
.check(status.is(202))
.check(
jsonPath(
"$.activityId").saveAs("message")
)
.check(bodyString.
transform(_.split("\""
)(3)).saveAs(
"changeToken"))
).exec(
session => {
val maybeId =
session.get(
"message").asOption[String]
println(maybeId)
session
}
)
}
}
但是这里使用feed时不会动态生成值。有人可以建议每次运行时如何生成随机数?
答案 0 :(得分:4)
请记住:如果您希望在Gatling构建场景时不仅在启动时评估一些代码,而是每次虚拟用户执行操作时,您都必须传递动态内容:基于Gatling EL的String或函数
在这里,您必须执行后者,例如:
.body(StringBody(session => //THIS IS A FUNCTION
s"""
|{
| "id": "activityId",
| "type": "run",
| "start_epoch_ms": "${randomStartMethod()}",
| "end_epoch_ms": "${randomStop()}",
| "metrics": [
| {
| "type": "distance",
| "unit": "KM",
| "source": "nike.running.ios",
| "values": [
| {
| "start_epoch_ms": "${randomStartMethod()}",
| "end_epoch_ms": "${randomStopMethod()}",
| "value": 2.0
| }
|
| ]
| }
| ]
|}
""".stripMargin))