Reputation: 1868
I have code that looks like so:
for (Map.Entry<Integer, Action> entry : availableActions.entrySet()) {
...
}
I've tried to mock it like this:
Map mockAvailableActions = mock(Map.class, Mockito.RETURNS_DEEP_STUBS);
mockAvailableActions.put(new Integer(1), mockAction);
I would think that would be enough. But entrySet is empty. So I added this:
when(mockAvailableActions.entrySet().iterator()).thenReturn(mockIterator);
when(mockIterator.next()).thenReturn(mockAction);
Still entrySet is empty. What am I doing wrong? Thanks for any input!
Upvotes: 20
Views: 101420
Reputation: 20254
Perhaps I'm missing something, but why not just do this:
Map.Entry<Integer, Action> entrySet = <whatever you want it to return>
Map mockAvailableActions = mock(Map.class);
when(mockAvailableActions.entrySet()).thenReturn(entrySet);
Also consider whether you actually need a mock Map at all, wouldn't a real one do the job? Mocks are usually used to replace other pieces of your code which you don't want to be involved in your unit test, a Map is part of the core Java language and isn't usually mocked out.
Upvotes: 31