Alex Luya
Alex Luya

Reputation: 9922

How to compose variable name dynamically?

I need to generate a list,and name it's items based on for-loop index number, like this:

for(int i=0;i<someNumber;i++){
    Model m_{$i}=Mock()   //but this doesn't work
    ......
    models.add(i,m_{$i})
}

then they can be distinguished by name when debugging test code(shame to tell this) within eclipse,but it doesn't work, so how to make it work?

update:add image to tell why I want to append for-loop index to variable name enter image description here

Upvotes: 0

Views: 1509

Answers (1)

Paweł Piecyk
Paweł Piecyk

Reputation: 2789

You can also add some property to your Mock class at runtime thanks to Groovy's MetaClass. Take a look at this sample snippet:

class myClass {
    String someProperty
}

def models = []
10.times { it ->
    def instance = new myClass(someProperty: "something")
    instance.metaClass.testId = it
    models.add(instance)
}

// delete some
println "Removing object with testId = " + models.remove(4).testId
println "Removing object with testId = " + models.remove(7).testId

def identifiersOfObjectsAfterRemoves = models.collect { it.testId }

def removedObjectsIdentifiers = (0..9) - identifiersOfObjectsAfterRemoves

println "Identifiers of removed objects: " + removedObjectsIdentifiers

Upvotes: 1

Related Questions