groovyassertionready-api

Groovy script assertion that validates the presence of some values in a JSON response


So I'm using an testing tool called ReadyAPI and for scripting it uses the Groovy language. I'm not familiar with the language and the fact that it's based on Java it somehow makes it even worse.

Now I'm trying to validate a REST response in JSON with an assertion that checks that certain elements exist in the response.

This is the code that I have now:

import groovy.json.*

def response = context.expand( 'RequestResponseHere' )
def object = new JsonSlurper().parseText(response)

assert response.contains("CODE1")
assert response.contains("CODE2")
assert response.contains("CODE3")
assert response.contains("CODE4")

The assertion seems to work but I was wondering if there is maybe a simpler way to do it than to have to write so many lines and making it less 'bulky'?

Any help is greatly appreciated.

Thank you!

Added an example of the json data that I have to parse: What I need is to check that the value of "code" is always part of a list of acceptable values e.i. CODE1, CODE2, etc.

{
    "_embedded": {
        "taskList": [
            {
                "code": "CODE1",
                "key": 123
            },
            {
                "code": "CODE2",
                "key": "234"
            },
            {
                "code": "CODE3",
                "key": "2323"
            },
            {
                "code": "CODE4",
                "key": "7829"
            },
            {
                "code": "CODE5",
                "key": "8992"
            }
        ]
    }
}

Solution

  • If you want to check for certain things to be there, you can DRY that code with:

    ["code1","code2"].each{ assert response.contains(it) }
    

    And as stated in the comments, if you want to make sure, "all are there, but I don't care for the order", extracting the values and comparing it as results can shorten this:

    assert response._embeded.taskList*.code.toSet() == ["code1", ...].toSet()
    

    Note the use of *., which is the "spread operator". It is basically the same as ...collect{ it.code }. Then comparing the string sets does the rest (this is fine if you are comparing not to many items since the power assert will print all the items along the failed assertion; if you have to find the proverbial needle in the haystack, you are better off writing something smarter to check the two sets).