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

Gatling foreach循环内保存数据至Session后无法读取报错问题

问题根因

你代码的核心错误是在Session自定义处理函数内部调用Gatling DSL的exec方法不会被实际执行。Gatling的DSL语句(包括exec封装的请求动作)是测试初始化阶段就预构建执行链的,你放在exec(session => { ... })函数体内的exec(getListOfStudents)只是创建了一个没有被加入执行链的孤立动作,实际运行时根本不会触发接口请求,自然不会往Session中写入listOfStudents字段,你后续读取该字段时就会抛出不存在的异常。

单班级场景运行正常的原因是该场景下getListOfStudents直接挂在全局执行链上,没有被包裹在Session处理函数内,会被正常调度执行,所以可以正常写入Session。

修复方案

将请求执行和Session更新的逻辑拆分到不同的exec块,按顺序挂载到执行链上即可:

val createMultiSectionEdCtsAssignment = repeat(2) {
  exec(getTeacherMultiSectionSectionId)
    .exec(session => session.set("listOfStudentsBySection", ""))
    .foreach(session => session("listOfSectionRefIds").as[String].split(',').toSeq, "sectionRefId") {
      // 第一步:先执行获取学生列表的请求,执行成功后会自动将listOfStudents写入Session
      exec(getListOfStudents)
      // 第二步:再执行Session更新逻辑,此时就能正常读取到刚写入的listOfStudents
      .exec(session => {
        val collectedStudents = collectStudents(session)
        val originalList = session("listOfStudentsBySection").as[String]
        val newList = if (originalList.isEmpty) collectedStudents else s"$originalList,$collectedStudents"
        session.set("listOfStudentsBySection", newList)
      })
    }
    .exec(session => session.set("assignmentType", "PROGRAM_ASSESSMENT"))
    .exec(createMultiSectionTeacherAssignment)
}

内容的提问来源于stack exchange,提问作者Swan-Work

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:09:05