Forum Discussion

CamillaR's avatar
CamillaR
Occasional Contributor
3 years ago
Solved

How to get request body using a groovy script in ReadyAPI

Hi,   The request (getDrafts) I'm testing takes a list of periods and reply with a list of data for those periods. Request body: {   "periods" : ["202101","202102"] }   Response body: {   "...
  • nmrao's avatar
    3 years ago

    CamillaR 

    This can achieved with Script Assertion for your REST Request test step. No separate Groovy Script test step is needed.

     

    You can access the request using

     

    //the following shows the request

    log.info context.request

     

    //he following shows the response

    log.info context.response

     

    Here you need to define the expected data as well for each period so that the same can be verified from the response.

     

    Please see the following complete script as per data you have provided

     

     

    //Closure to parse the json text 
    def getJson = { new groovy.json.JsonSlurper().parseText(it) }
    
    //Get the periods from request
    def expectedPeriods = getJson(context.request).periods
    
    //You can modify the expected data if needed, this is as per the sample
    def expectedData = [202101:[name: 'Kalle Kula', epost: 'kalle@kula.se'], 202102: [name: 'Krille Krokodil', phone: '9876543210']]
    
    //Get the response parsed 
    def json =  getJson(context.response)
    
    //Verify if the response has both the periods
    assert expectedPeriods == json.drafts.period
    
    //Loop thru each period of request and get the respective data from response and verify
    expectedData.keySet().each { period ->
        log.info "Expected data for ${period}: ${expectedData[period]}"
        log.info "Actual data for ${period}: ${json.drafts.find{it.period == "$period"}.data}"
        //Test if they matching
        assert expectedData[period] == json.drafts.find{it.period == "$period"}.data
    }

     

     

    Here you can test it online with fixed data that was provided in the question.

    https://ideone.com/OZmvie

     

    However, the above script assertion shall work for the dynamic response that you receive provided if change the expected data as per your actual data.