JMeter中如何比较提取的布尔值?Groovy代码异常排查

问题梳理
- 基于Groovy编写数据处理逻辑,现有代码第10、13、15行运行报错
- 待处理的
Combined、groupbilling两个字段返回值均为Boolean类型 - 目标需求:获取同一索引位置下,两个字段值同时为
true的对应索引值
报错根因
这类行号的运行异常基本是三类问题导致:
- 下标取值时未做越界校验,触发索引越界异常
- 直接用
== true做判断时,若字段值为null,Groovy自动拆箱会触发空指针 - 遍历逻辑未正确关联索引与对应位置的两个字段值,导致判断逻辑不生效
可直接复用的实现方案
根据你数据源结构的不同,选对应写法即可:
方案1:两个字段分别存储在两个等长列表中
假设combinedList按索引顺序存储所有Combined字段值,groupbillingList按索引顺序存储所有groupbilling字段值:
// 替换为你实际的数据源 def combinedList = [true, false, true, true] def groupbillingList = [true, true, false, true] def validIndexes = [] combinedList.eachWithIndex { Boolean combinedVal, int idx -> // 先校验下标合法性,再用equals判断布尔值,避免空指针和越界 if (idx < groupbillingList.size() && Boolean.TRUE.equals(combinedVal) && Boolean.TRUE.equals(groupbillingList[idx])) { validIndexes << idx } } // 最终validIndexes即为所有符合要求的索引集合,示例数据返回[0, 3]
方案2:数据源为对象/Map构成的列表,每个元素对应一个索引位的完整数据
假设dataList中每个元素都包含Combined、groupbilling两个属性:
// 替换为你实际的数据源 def dataList = [ [Combined: true, groupbilling: true], [Combined: false, groupbilling: true], [Combined: true, groupbilling: false], [Combined: true, groupbilling: true] ] // 写法1:手动遍历收集 def validIndexes = [] dataList.eachWithIndex { def item, int idx -> if (Boolean.TRUE.equals(item.Combined) && Boolean.TRUE.equals(item.groupbilling)) { validIndexes << idx } } // 写法2:用Groovy内置API简化,无需手动初始化集合 def validIndexesSimple = dataList.findIndexValues { Boolean.TRUE.equals(it.Combined) && Boolean.TRUE.equals(it.groupbilling) }
避坑提示
- 禁止直接写
if (item.Combined == true && item.groupbilling == true)这类判断,只要任意一个字段值为null就会抛空指针,用Boolean.TRUE.equals()是Groovy中判断布尔值最稳妥的写法,兼容null场景 - 如果你的数据源是数组,逻辑完全一致,只需要把列表的长度判断换成数组的
.length属性即可
内容的提问来源于stack exchange,提问作者yazhdevi subramani
相关产品推荐
相关产品推荐

