Search code examples
arraysjsongroovyjsonslurper

How to assert array json in groovy


My JSON response looks like below

{
    "pCategories": [
        "pogc1",
        "pogc16",
        "pogc2",
        "testc1122",
        "testcat10012018",
        "testcat10012019",
        "testcat100120191",
        "testcat11012018",
        "testcat12012018",
        "testcat120120181",
        "testcat20112017",
        "testcat20112018"
    ]
}

I have used the below code to assert.

def slurped = new JsonSlurper().parseText(response.asString())
assert slurped.pCategories.contains("$category")

But getting an error.

How do I resolve it?


Solution

  • Because "$category" is not a String. It is an instance of GStringImpl.

    def category = 'pogc16'
    assert 'pogc16'.equals("$category") // false
    

    To fix your code you can convert "$category" to String:

    assert slurped.pCategories.contains("$category".toString())