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

如何让Gatling断言在数值差值不超过1.00时通过?

解决方案

你的代码编译失败主要有三个核心问题:

  • actualValue类型未明确为String,导致无法直接调用字符串方法
  • 框架中Session的取值方法并非get,需使用类型安全的getAttribute(假设你基于Gatling测试框架)
  • 正则表达式中的$是特殊元字符,未转义无法匹配字面量$

下面是修正后的可运行代码:

.check(
  jsonPath("$.data.attributes.contentValue")
    // 显式转换为String,确保后续字符串操作合法
    .transform(val -> String.valueOf(val))
    .validate((actualStr, session) -> {
      // 转义$字符,清理数值中的$和逗号
      String cleanedNumStr = actualStr.replaceAll("\\$", "").replace(",", "");
      double actualDouble = Double.parseDouble(cleanedNumStr);
      // 从Session中安全获取预期数值
      double expectedDouble = session.getAttribute("expectedDoubleValue");
      // 判断差值是否在允许范围内
      return Math.abs(expectedDouble - actualDouble) <= 1.00;
    })
)

关键修正说明:

  • 类型明确转换:通过transform强制将JSON路径获取的值转为String,避免类型歧义
  • 正则转义修复:将replaceAll("$", "")改为replaceAll("\\$", ""),$在正则中表示行尾,必须转义才能匹配字符串中的美元符号
  • Session取值规范:使用框架标准的getAttribute方法获取Session中的预期值,无需强制类型转换(前提是存入时已为Double类型)

如果contentValue在JSON中本身就是数值类型(非字符串),可以简化为:

.check(
  jsonPath("$.data.attributes.contentValue")
    .transform(val -> (Double) val)
    .validate((actualDouble, session) -> {
      double expectedDouble = session.getAttribute("expectedDoubleValue");
      return Math.abs(expectedDouble - actualDouble) <= 1.00;
    })
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:27:41