Forum Discussion

annedemata's avatar
annedemata
New Contributor
7 years ago

How to assert count of a certain field in a JSON response is not equal to 0

The attached snapshot shows the format of my JSON response and the assertion that I would like to have is a simple one which would pass if the clients node is not empty. I was thinking of something like $['clients'].length() != 0 but I can't seem to make this work. I'm not sure if there is a predefined assertion I can use (JSONPath Match???) or if my only option is to use Groovy Scripting (which I've never done before). Thanks!

2 Replies

  • Lucian's avatar
    Lucian
    Community Hero

    There is a special assertion type that does just that namely the JsonPath Existence Match. You can set an assertion as below and you're ready to go:

     

  • If you just need to check that clients has child elements, I would use a Groovy script assertion. Add the assertion, right-click in the script editor and then click Get Data. Choose the test step that returns this JSON, then select 'Response' and select the clients node.

     

    It will then add something like this to the editor:

    def response = context.expand( '${Your step name#Response#$[\'clients\']}' )

    response will be a string, but you can use Groovy truth to determine that it is not empty/null by doing

    assert (response)

    If clients has no children, this assertion will fail