HackerGil HackerGil - 6 months ago 70
Java Question

Testing Java enhanced for behavior with Mockito

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

public void test()
List<String> mockList = Mockito.mock(List.class);
Iterator<String> mockIterator = Mockito.mock(Iterator.class);


boolean flag = false;
for(String s : mockList) {
flag = true;

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.


Mocking the iterator works for me. See below code sample:

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Collection;
import java.util.Iterator;

import org.junit.Before;
import org.junit.Test;

public class TestMockedIterator {

    private Collection<String> fruits;
    private Iterator<String> fruitIterator;

    public void setUp() {
        fruitIterator = mock(Iterator.class);
        when(fruitIterator.hasNext()).thenReturn(true, true, true, false);

        fruits = mock(Collection.class);

    public void test() {
        int iterations = 0;
        for (String fruit : fruits) {
        assertEquals(3, iterations);