0

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

7
  • 3
    Why would you like to do it like that? Maybe Map would be better in this case? Commented Aug 11, 2014 at 7:55
  • Also, can't you just get the one you're after by querying eg: models[1] rather than m_1? Commented Aug 11, 2014 at 7:56
  • For debugging test code(shame to tell this),but please tell me this is possible or not? Commented Aug 11, 2014 at 8:21
  • During test code execution,some item will be added or removed,so I need to know which is added or removed? Commented Aug 11, 2014 at 8:23
  • How they are going to be removed? From models list? Commented Aug 11, 2014 at 8:32

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks,I am very appreciate your answer,but I am using spock to test java code,and this list will be passed into java object,and I can't changed java code.is it impossible due to nobody provide a direct answer?
I've just updated my answer. Maybe this time it will be more helpful :)
I am not sure whether any property can be add to Mock object.(I will check it).So it is impossible to combine index to item name.if it is possible,the thing will be far more easy than this.
It's possible thanks to MetaClass property (linked in my answer). Check it and we'll see if it's good method to deal with your problem.
Thanks,your answer still can't solve my problem(I added an image to tell why),but it is good enough for my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.