Search code examples
groovyreflectionautomated-testsspock

Setting member variables by name in Spock


I am writing a Spock integration test for a function that takes a DTO, that has a lot of member variables. The functionality to test is that one user role is allowed to change some member variables, but if that user tries to change one of the other fields, it should fail.

I don't want to manually write a test for every single field, so I figured, I could be using a where: table like so:

where:
fieldname | value | isAccepted
"fieldA"  | "val" | true
"fieldB"  | "val" | false
...

For that, I'd have to be able to set the fields by the name in a string. In Java I'd have to use reflection for that. In Python I could just use setattr(object, fieldname, value) for that.

Since I writing the test in Groovy, is there something idiomatic for that?


Solution

  • Yes there is an idiomatic way to dynamically access fields an methods in groovy. You just use a GString to reference the field.

    class A {
        String foo = 200
        String bar = 400
    }
    
    def a = new A()
    def field = "foo"
    println a."$field"
    field = "bar"
    println a."$field"
    a."$field" = 600
    println a.bar
    

    Outputs

    200
    400
    600
    

    Test it in the Groovy Web Console