Forum Discussion

Hellotest's avatar
4 years ago

Getting error with dynamic extractions in Groovy script

Hello, In Groovy Script trying to extract value from API Response . Instead of getting first value in Json trying to extract dynamically by referring to its value from datasource. Ex- def sourceI...
  • nmrao's avatar
    4 years ago

    Hellotest wrote:

    I tried first with out datasource as below but getting null pointer error as attached. 


    import static com.jayway.jsonpath.JsonPath.parse
    def jsonString = context.expand( '${GetSources#Response}' )
    def sourceId = new groovy.json.JsonSlurper().parseText(jsonString).result.find{it.SourceCode == 'ABC'} "source id: ${sourceId.SourceId}"


    You almost there, but trivial errors.




    //Get the parsed json of GetSources test step response
    def json = new groovy.json.JsonSlurper().parseText(context('${GetSources#Response}'))
    //Closure to the the SourceId for a given SourceCode of the json
    def getSourceIdBySourceCode = { code ->  json.find {it?.SourceCode == code}?.SourceId }
    //Check if the value is matching
    assert 'b4035134-ca33-4b33-b3c7-06ea880f1f28' == getSourceIdBySourceCode( 'DEF')
    assert 'bc3cef1e-a9f1-46df-a4f0-c1131357ea57' == getSourceIdBySourceCode( 'ABC')




    You can test it online here