Forum Discussion

sonya_m's avatar
sonya_m
SmartBear Alumni (Retired)
5 years ago

[TechCorner Challenge #3] How to Go Through All Response Nodes and Check Value of Required Field

Hi Community!   Here’s a new challenge the results of which will make lives of many ReadyAPI users easier.   When working with dynamic responses, testers often need to create Groovy script as...
  • nmrao's avatar
    5 years ago

    Task: Write a script for the script assertion (for the REST test step) which will go through all response nodes and compare the value of the name field with the required value. The number of nodes is dynamic.

     

    This is a solution created for [TechCorner Challenge #3]

     

    Similar question answered numerous times in the forum I believe.

     

    Taking little different json (but with same structure as given in the question) for better understanding.

     

    Assume that user received the below json as response, say get cars.

     

     

     

    {
      "cars": [
        {
          "name" : "Jetta",
          "brand" : "Volkswagen"
        },
        {
          "name" : "Polo GT",
          "brand" : "Volkswagen"
        },
        {
          "name" : "i30",
          "brand" : "Hyundai"
        }
      ]
    }

     

     

     

    Now he wants to assert cars of brand "Volkswagen"

     

    Here goes the script assertion for the getCars REST call

     

     

     

     

    //User looking for below data in the response
    def brandToCheck = 'Volkswagen'
    def expectedCars = ['Jetta', 'Polo GT']
    
    //to read dynamic response; you can test it with fixed json as well
    def jsonText = context.response 
    
    //Get all the cars
    def cars = new groovy.json.JsonSlurper().parseText(jsonText).cars
    
    //Verify if the expectedCars in the response for the given brand
    assert expectedCars == cars.findAll { it.brand == brandToCheck }.name, 'Not matching the expected cars'
    

     

     

     

     

    Another test can be validate the brand of a car name, say i30

     

     

     

    //User want to validate brand of i30
    assert 'Hyundai' == cars.find { it.name == 'i30'}.brand, 'Not matching the brand for i30 car'

     

     

     

    One can test it online (but using fixed json)

    https://ideone.com/CaLMHy