List of Java listings in mockito thenReturn

Is there a way to list the items in a list in the mockito thenReturn function so that I return every item in the list. So far I have done this:

List<Foo> returns = new ArrayList<Foo>(); //populate returns list Mockito.when( /* some function is called */ ).thenReturn(returns.get(0), returns.get(1), returns.get(2), returns.get(3)); 

It works exactly the way I want it. Each time a function is called, it returns another object from the list, for example get(1) , get(2) , etc.

But I want to simplify this and make it more dynamic for any list of sizes, if I have a list of size 100. I tried something like this:

 Mockito.when( /* some function is called */ ).thenReturn( for(Foo foo : returns) { return foo; } ); 

I also tried this:

 Mockito.when(service.findFinancialInstrumentById(eq(1L))).thenReturn( for (int i=0; i<returns.size(); i++) { returns.get(i); } ); 

But this will not work ... since I list this list in thenReturn .... I came across other methods like then or answer , but I do not work best in this scenario.

+5
source share
2 answers

Another way to do this (but personally, I prefer the idea of ​​JB Nizet SequenceAnswer) would be something like this ...

 OngoingStubbing stubbing = Mockito.when(...); for(Object obj : list) { stubbing = stubbing.thenReturn(obj); } 
+11
source

Signature of thenReturn () Method

 thenReturn(T value, T... values) 

Thus, it takes an instance of T, followed by vararg T ..., which is the syntactic sugar for the array. So you can use

 when(foo.bar()).thenReturn(list.get(0), list.subList(1, list.size()).toArray(new Foo[]{})); 

But a cleaner solution would be to create an implementation of the response that takes the List argument as an argument and responds to the next list item each time it is used. And then use

 when(foo.bar()).thenAnswer(new SequenceAnswer<>(list)); 

For instance:

 private static class SequenceAnswer<T> implements Answer<T> { private Iterator<T> resultIterator; // the last element is always returned once the iterator is exhausted, as with thenReturn() private T last; public SequenceAnswer(List<T> results) { this.resultIterator = results.iterator(); this.last = results.get(results.size() - 1); } @Override public T answer(InvocationOnMock invocation) throws Throwable { if (resultIterator.hasNext()) { return resultIterator.next(); } return last; } } 
+13
source

Source: https://habr.com/ru/post/1234402/


All Articles