You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gatling-Scala:如何重复请求直到API响应中无指定响应变量?

解决游标分页API循环测试的响应检查问题

核心问题分析

你当前的请求里强制用.check(jsonPath("$.nextCursor").exists)校验nextCursor必须存在,但最后一页的API响应里不会返回这个字段,所以循环到最后一次请求时就会触发校验失败,抛出你看到的错误。

具体修复方案

1. 调整响应校验逻辑

把强制校验nextCursor存在改为可选校验,同时用saveAs获取并存储游标值,供下一次循环使用:

.exec(http("APITests:Cursor Pagination")
  .get("/testapi")
  .queryParam("sortField", "ID")
  .queryParam("limit", limitCount)
  .queryParam("cursor", "#{CursorID}")
  .check(status.is(200))
  // 可选获取nextCursor,不存在时不会报错,存到变量中
  .check(jsonPath("$.nextCursor").optional.saveAs("nextCursor"))
)

2. 修正doWhile循环的终止条件

循环要在nextCursor为空或不存在时停止,所以判断条件要检查这个变量的有效性:

doWhile(session => session.contains("nextCursor") && session("nextCursor").as[String].nonEmpty, "loopCount") {
  exec(/* 上面修改后的请求 */)
  // 将新获取的游标赋值给下一次请求要用的CursorID
  .exec(session => session.set("CursorID", session("nextCursor").as[String]))
}

3. 初始化游标变量

循环开始前要给CursorID设置初始值(比如空字符串,若API第一次请求不需要cursor参数,可后续处理参数传递逻辑):

.exec(session => session.set("CursorID", ""))

完整示例代码

val scn = scenario("Cursor Pagination Test")
  .exec(session => session.set("CursorID", "")) // 初始化游标变量
  .doWhile(session => session.contains("nextCursor") && session("nextCursor").as[String].nonEmpty, "loopCount") {
    exec(http("APITests:Cursor Pagination")
      .get("/testapi")
      .queryParam("sortField", "ID")
      .queryParam("limit", limitCount)
      // 仅当CursorID不为空时才传递该参数,避免第一次请求传无效值
      .queryParamMap(session => 
        if (session("CursorID").as[String].nonEmpty) Map("cursor" -> session("CursorID").as[String]) 
        else Map.empty
      )
      .check(status.is(200))
      .check(jsonPath("$.nextCursor").optional.saveAs("nextCursor"))
    )
    .exec(session => {
      // 打印日志方便调试,可按需删除
      println(s"当前游标: ${session("CursorID").as[String]}, 下一页游标: ${session("nextCursor").asOption[String].getOrElse("无")}")
      session.set("CursorID", session("nextCursor").asOption[String].getOrElse(""))
    })
  }

额外注意事项

  • 若API第一次请求不允许传空的cursor参数,一定要用条件判断跳过该参数,避免触发API的参数校验错误。
  • 建议给循环添加次数上限(比如session("loopCount").as[Int] < 100),防止因API异常导致无限循环,需提前初始化loopCount变量。

内容的提问来源于stack exchange,提问作者Monika Rajendran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 21:15:33