Mocking a list and iterator with a foreach loop

20,590 views
Skip to first unread message

BenT

unread,
May 26, 2011, 1:00:56 AM5/26/11
to mockito
It is my understanding that the for(element : list) syntax grabs the
iterator from the list via list.iterator(), and as long as
iterator.hasNext() is true, invokes iterator.next() for the element.
So here is my supporting to code to mock this interaction:


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> mockIter = Mockito.mock(Iterator.class);

when(mockList.iterator()).thenReturn(mockIter);
when(mockIter.hasNext()).thenReturn(true);
when(mockIter.next()).thenReturn("A");
when(mockIter.hasNext()).thenReturn(false);

boolean flag = false;

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

assertTrue(flag);
}
}


The trouble is that this test fails, as the body of the loop is never
executed.

Any help would be appreciated.

Kristofer Karlsson

unread,
May 26, 2011, 2:45:40 AM5/26/11
to moc...@googlegroups.com
You're overwriting the first definition with hasNext with the second definition.
You'd really want to do something like: when(mockIter.hasNext()).thenReturn(true);thenReturn(false);

However, I think it seems a bit unnecessary to mock a list instead of using a real list (possibly using a spy on a list, if you want to capture interactions)



--
You received this message because you are subscribed to the Google Groups "mockito" group.
To post to this group, send email to moc...@googlegroups.com.
To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mockito?hl=en.


Ben Tomasini

unread,
May 26, 2011, 10:05:10 PM5/26/11
to moc...@googlegroups.com
Thanks for the clarification and the usage advice. The example is a
trivial one. In my actual use case I am testing an assertion method
which checks if the provided list is unmodifiable given all possible
interactions with the list.
Reply all
Reply to author
Forward
0 new messages