Is possible mock set so after use in cycle e.g.
for(String key: mySet) { ...}
Thanks.
Is possible mock set so after use in cycle e.g.
for(String key: mySet) { ...}
Thanks.
There is a couple options:
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...
}
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();
}
});