1

I am using Groovy to create a package that I use in ReadyApi.

In a Groovy script test step, I do the following:

class B  {
    String value
    boolean isSomething
}

class A {
    String name
    B propB

    public A() {
        this.name = "Maydan"
    }
}

def x = (A) new A().with  { propB = new B(value: "Abc", isSomething: true) }

And I get the following error:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'B@6c218cea' with class 'B' to class 'A' error at line: 15

Does someone know why? It doesn't make any sense to me.

Kind regards.

PS: I would like to create an instance of class A (by using its parameterless constructor) and setting its field propB in a single statement

Aymen Turki
  • 105
  • 2
  • 10

1 Answers1

1

You need to return your A object from the .with closure. You may do it like that:

def x = (A) new A().with  { propB = new B(value: "Abc", isSomething: true); return it}

but to me personally it looks a little bit odd. I would do it like that:

def x = new A(propB: new B(value: "Abc", isSomething: true))

The same effect, but more compact and readable. It doesn't require to change your A and B definitions, this "map constructor" works out of the box in Groovy, it will call your parameterless constructor and then assigns the necessary fields (propB in your case).

Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22
  • Thank you very much! My understanding was biased by my knowledge of C# object-initializers (since I am normally a C# dev). (By the way, the second solution doesn't fit my needs since I want to call the parameterless constructor defined in A) – Aymen Turki Jan 30 '23 at 11:13
  • 1
    @AymenTurki I've updated my answers, you do not need to re-define A or B, it will work for you without any changes as you want it. It's Groovy syntax sugar. – Andrej Istomin Jan 30 '23 at 11:15