我想对JMeter中表示如下的JSON数组执行断言测试:
{
"item": [
{
"id": "cx34ty1",
"name": "xyzitem",
"isSerialNoRequired": false,
"itemProps": {
"type": "readonly",
"count": 10
}
}
]
}
例如,我知道可以使用JSR223断言来断言密钥的存在。在这种情况下,“ item”使用:
if (!jsonResponse.keySet().containsAll(["item"])) {
failureMessage += "The json config element has wrong structure.\n\n";
如果要断言数组中是否存在键,应该怎么办? “ id”或“ itemProps”?另外,鉴于JSON断言是资源密集型的,我也不想使用它,因为我还想检查多个键。
答案 0 :(得分:0)
您可以使用相同的方法,例如:
def jsonResponse = new groovy.json.JsonSlurper().parse(prev.getResponseData())
if (!jsonResponse.keySet().contains('item')) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('"item" element was not found')
}
if (!jsonResponse.item.get(0).keySet().contains('id') || !jsonResponse.item.get(0).keySet().contains('itemProps')) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('"id" or "itemProps" element was not found')
}
但是,您可以提出更好的解决方案,例如使用JSON Schema Validator库,如果下载.jar并将其放入JMeter Classpath,则可以针对预定义的JSON响应进行测试JSON Schema,如果不匹配(缺少必填键或值的数据类型错误),您将收到通知。
更多信息: