在ReadyAPI中用Groovy断言JSON数组排序及首尾元素问题
在ReadyAPI中断言JSON数组按指定属性字母排序的解决方案
当前你的代码仅校验了数组首尾元素的属性值,无法确保整个数组严格按foundPatientDisplayNaam属性的字母顺序排序。以下是两种可靠的实现方案:
方案一:对比原属性列表与排序后的列表
这种方法简洁直观,适合大多数场景:
// 解析JSON响应内容 def json = new groovy.json.JsonSlurper().parseText(context.response) // 提取数组中所有元素的目标属性,生成字符串列表 def originalNames = json.data.collect { it.foundPatientDisplayNaam } // 生成按默认字母顺序排序后的列表(false表示不修改原列表) def sortedNames = originalNames.sort(false) // 断言原列表与排序后的列表完全一致,不一致则抛出指定提示 assert originalNames == sortedNames : "数组未按foundPatientDisplayNaam属性字母顺序排序"
方案二:遍历数组逐一比较相邻元素
适合处理大型数组,一旦发现无序元素可提前终止校验,提升效率:
def json = new groovy.json.JsonSlurper().parseText(context.response) def dataList = json.data def isSorted = true for (int i = 0; i < dataList.size() - 1; i++) { def currentName = dataList[i].foundPatientDisplayNaam def nextName = dataList[i+1].foundPatientDisplayNaam // 比较相邻元素的属性值,若当前元素大于下一个则标记为无序 if (currentName.compareTo(nextName) > 0) { isSorted = false break } } // 断言数组有序,失败时输出具体异常位置和元素值 assert isSorted : "数组未按foundPatientDisplayNaam属性字母顺序排序,位置${i}的元素${currentName}大于位置${i+1}的元素${nextName}"
注意事项
- 大小写处理:默认排序区分大小写,若需忽略大小写,将
compareTo替换为compareToIgnoreCase,排序时改为originalNames.sort(false) { a, b -> a.compareToIgnoreCase(b) } - 非空校验:若存在元素的
foundPatientDisplayNaam属性为空,可在断言前添加校验:assert json.data.every { it.foundPatientDisplayNaam != null } : "存在元素的foundPatientDisplayNaam属性为空"
内容的提问来源于stack exchange,提问作者Philip Stuij
相关产品推荐
相关产品推荐

