Submit and vote on feature ideas.

Welcome to the new Parasoft forums! We hope you will enjoy the site and try out some of the new features, like sharing an idea you may have for one of our products or following a category.

Groovy - Asserting that all JSON response elements have content

Options
Gambit
Gambit Posts: 28

I have a test scenario with hundreds of response elements and I am trying to script an assertion to ensure that none of the elements returned as null. There must be an easy way to use a wildcard to search the entire response body for a null field, but I can't figure out how to do it. Can anyone suggest a better solution to ensure no nulls were returned?

Response snippet:
{
"errors" : [
],
"transactionId" : "123456789",
"dateTime" : "2017-12-08T22:07:43.099Z",
"observed" : {
"date" : "2017-12-08",
"obs" : 39,
"conditions" : {
"text" : "Clear",
"code" : 85
}
},
etc.....

And the code I have so far:
import com.parasoft.api.*
import groovy.json.JsonSlurper
import java.util.*
import soaptest.api.*

void extractAndAssertResponse(Map input, ScriptingContext context) {
def slurper = new JsonSlurper()
String responseBody = input.get(SOAPUtil.XML_RESPONSE)
Application.showMessage("RESPONSE_BODY: " + responseBody)

    def json = slurper.parseText(responseBody)
    assert json.transactionId != null
    assert json.dateTime != null
    assert json.observed.date != null

}

Tagged:

Comments

  • OmarR
    OmarR Posts: 234 admin
    Options

    Hello Gambit,

    If you don't expect "null" to be anywhere in your payload, it may be easier to use the "Search Tool" to throw an error if the particular string is found. For example:

  • Gambit
    Gambit Posts: 28
    Options

    Hi OmarR,

    The search tool looks like it would work fine for the literal "null" field value, but how would I account for the scenario of a return of ""?

  • OmarR
    OmarR Posts: 234 admin
    Options

    You could add "" as one of the search terms in the tool.
    For example:

    The Json Assertor could also accomplish the same for specific elements in the payload:

    Give these tools a try and let us know if you have any questions about them :)

  • Gambit
    Gambit Posts: 28
    Options

    Hi Omar,

    I've tested this solution and it works for my problem. Thanks!