2

I am using a groovy script within a Ready API test case to validate the results in a json web service response.

I want to use a variable (that is specified within a data source) to specify the json path that I want to validate, as this may change for each test run.

The following bit of code correctly assigns all the data referred to by the path results.address_components.long_name to the variable 'actualResponseOne'

def actualResponseOne =  jsonSlurper.results.address_components.long_name.collect()

But, because within the same test I might want to validate different json elements ie. results.geometry.location_type for example I don't want to have the path hardcoded within the groovy script but instead set it up in a data source and assign it to a groovy variable within my script with ..

def testElementOne1   = context.expand( '${DataSource-Groovy-GoogleMaps#testElement1}' );

How to I refer to this json path within my code that assigns the data to 'actualResponseOne'? The below code doesn't work.

def actualResponseOne =  jsonSlurper.${testElementOne}.collect()

Any help would be much appreciated.

regards,

Tam.

chucknor
  • 837
  • 2
  • 18
  • 33

2 Answers2

0

The way I understand it is that GPath doesn't traverse dots [See this stack overflow question and this Groovy language bug]. You may have to break out the Eval class to force that to be evaluated. Perhaps something like?

ourPath = "results.address_components.long_name"
Eval.x( ourPath, "jsonSlurper.${x}.collect()" )
lepe
  • 24,677
  • 9
  • 99
  • 108
RyanWilcox
  • 13,890
  • 1
  • 36
  • 60
0

An alternative to using Eval would be to add a helper method to break apart the path and traverse it iteratively:

class Nested {
    static class A {
        B b
    }
    static class B {
        C c
    }
    static class C {
        List list
    }
    static void main(String[] args) {
        def a = new A(b: new B(c: new C(list: [1, 2, 3])))
        println getNestedProperty(a, "b.c.list").collect { String.format "%03d", it }
    }

    static def getNestedProperty(def object, String path) {
        path.split(/\./).each {
            object = object."${it}"
        }
        return object
    }
}

[001, 002, 003]

Raniz
  • 10,882
  • 1
  • 32
  • 64