I want to make the following work, but I don't know how to mock forEach behavior properly. (The code is taken from a related question Testing Java enhanced for behavior with Mockito )
@Test
public void aa() {
Collection<String> fruits;
Iterator<String> fruitIterator;
fruitIterator = mock(Iterator.class);
when(fruitIterator.hasNext()).thenReturn(true, true, true, false);
when(fruitIterator.next()).thenReturn("Apple")
.thenReturn("Banana").thenReturn("Pear");
fruits = mock(Collection.class);
when(fruits.iterator()).thenReturn(fruitIterator);
doCallRealMethod().when(fruits).forEach(any(Consumer.class));
// this doesn't work (it doesn't print anything)
fruits.forEach(f -> {
mockObject.someMethod(f);
});
// this works fine
/*
int iterations = 0;
for (String fruit : fruits) {
mockObject.someMethod(f);
}
*/
// I want to verify something like this
verify(mockObject, times(3)).someMethod(anyString());
}
Any help will be very appreciated.