I want to test a java method that has an enhanced for on it using Mockito. The problem is that when I don't know how to set the expectations for the enhanced for to work. The following code was gotten from an unanswered question in the mockito google group:
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.mockito.Mockito;
import org.testng.annotations.Test;
public class ListTest
{
@Test
public void test()
{
List<String> mockList = Mockito.mock(List.class);
Iterator<String> mockIterator = Mockito.mock(Iterator.class);
when(mockList.iterator()).thenReturn(mockIter);
when(mockIter.hasNext()).thenReturn(true).thenReturn(false);
when(mockIter.next()).thenReturn("A");
boolean flag = false;
for(String s : mockList) {
flag = true;
}
assertTrue(flag);
}
}
The code inside the for loop never gets executed. Setting expectations for an iterator doesn't work, because the java enhanced for doesn't use the list iterator internally. Setting expectations for List.get()
method doesn't either since the enhanced for implementation doesn't seem to call the get()
method of the list either.
Any help will be much appreciated.