I want to perform an assertion test on a JSON array represented as follows in JMeter:
{
"item": [
{
"id": "cx34ty1",
"name": "xyzitem",
"isSerialNoRequired": false,
"itemProps": {
"type": "readonly",
"count": 10
}
}
]
}
I know that it is possible to assert for the presence of a key using JSR223 assertion, for eg. "item" in this case using:
if (!jsonResponse.keySet().containsAll(["item"])) {
failureMessage += "The json config element has wrong structure.\n\n";
What should I do if I want to assert for the presence of a key within the array, or eg. "id" or "itemProps"? Also, given that JSON Assertion is resource intensive, I don't want to use it since I also want to check for multiple keys.
You can use the same approach, like:
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')
}
However you could come up with a better solution, for example use JSON Schema Validator library, if you download the .jar and put it to JMeter Classpath you will be able to test JSON response against pre-defined JSON Schema and in case of mismatch (missing mandatory key or wrong data type of value) you will be notified.
More information: