19

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!

Jonathan
  • 20,053
  • 6
  • 63
  • 70
CNDyson
  • 1,687
  • 7
  • 28
  • 63

1 Answers1

31

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.

codebox
  • 19,927
  • 9
  • 63
  • 81