Although Nicholas's answer clearly explains how you are mocking Set, I think your question also implies that you want to mock the behavior of the set during the loop.
To do this, you first need to know that your code is only syntactic sugar and extends to:
for (Iterator iterator = mySet.iterator(); iterator.hasNext();) { String key = (String) iterator.next(); ... }
(For more on this, see the Stackoverflow question. Which is more efficient for each loop or iterator? )
This makes it clear that you need to make fun of the iterator() method. After you customize the layout as described by Nicholas, you mock the iterator as follows:
when(mySet.iterator()).thenAnswer(new Answer<Iterator<String>>() { @Override public Iterator<String> answer(InvocationOnMock invocation) throws Throwable { return Arrays.asList("A", "B").iterator(); } });
leo
source share