Is there a way to enumerate the items in a list within mockito's thenReturn function so I return each item in a list. So far I've done this:
List returns = new ArrayList();
//populate returns list
Mockito.when( /* some function is called */ ).thenReturn(returns.get(0), returns.get(1), returns.get(2), returns.get(3));
This works exactly how I want it to. Each time the function is called, it returns a different object from the list, e.g get(1), get(2) etc.
But I want to simplify this and make it more dynamic to any size list in case I have a list with size say 100. I tried something like this:
Mockito.when( /* some function is called */ ).thenReturn(
for(Foo foo : returns) {
return foo;
}
);
I've tried this as well:
Mockito.when(service.findFinancialInstrumentById(eq(1L))).thenReturn(
for (int i=0; i
returns.get(i);
}
);
But this doesn't work....so how do I enumerate this list within the thenReturn....I've come across other methods to like then or answerbut I'm not sure which one works best in this scenario.
解决方案
Another way of doing it (but personally, I prefer JB Nizet SequenceAnswer idea), would be something like this...
OngoingStubbing stubbing = Mockito.when(...);
for(Object obj : list) {
stubbing = stubbing.thenReturn(obj);
}