Search code examples
unit-testingmockingjmockit

Partial mocking in JMockit for each element in the Collection


I am using JMockit 1.10 and need to partially mock out a method for each element in a Collection.

I am able to do that if I pass them separately to new NonStrictExpectation like

final Object obj1 = objs.get(0);
final Object obj2 = objs.get(1);
new NonStrictExpectations(obj1, obj2) {{
    ...
}};

However it complains "Class is already mocked" if I pass them in a loop.

for (int i = 0; i < 2; i++) {
    final Object _obj = objs.get(i);
    new NonStrictExpectations(_obj) {{
    }};
}

May I know why? Or what is the proper way to do it?


Solution

  • Without more information about what you're really trying to achieve, my guess is that the proper solution here is to partially mock the class of the elements in the collection, therefore mocking all such instances. Also, expectation blocks should never be created in a loop; there are other ways to deal with multiple invocations to the same mocked method.