7

Is possible mock set so after use in cycle e.g.

for(String key: mySet) { ...}

Thanks.

user710818
  • 23,228
  • 58
  • 149
  • 207

2 Answers2

13

There is a couple options:

  1. Cast it
  2. Use @Mock annotation

Examples:

Set<String> mySet = (Set<String>) mock(Set.class);

--or--

@Mock
private Set<String> mySet;

@Before
public void doBefore() throws Exception {
    MockitoAnnotations.initMocks(this.getClass()); //this should create mocks for your objects...
}
leo
  • 3,677
  • 7
  • 34
  • 46
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
9

While in the answer from nicholas is perfectly clear explaining how you mock a Set, I think your question also implies that you want to mock the behavior of the set during the loop.

To achieve that you first need to know that your code is only syntactic sugar and expands to:

for (Iterator iterator = mySet.iterator(); iterator.hasNext();) { 
    String key = (String) iterator.next(); 
    ...
}

(For details about that see the Stackoverflow question Which is more efficient, a for-each loop, or an iterator?)

This makes clear that you need to mock the iterator() method. After you set up the mock as described by nicholas you mock the iterator method like this:

when(mySet.iterator()).thenAnswer(new Answer<Iterator<String>>() {
   @Override
   public Iterator<String> answer(InvocationOnMock invocation) throws Throwable {
      return Arrays.asList("A", "B").iterator();
   }
});
Community
  • 1
  • 1
leo
  • 3,677
  • 7
  • 34
  • 46