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!
With Mockito, you create a mock, tell Mockito what to do when specific methods are called on it, and then use the mock instance in your test instead of the real thing. After the test, you can query the mock to see what specific methods were called or check the side effects in the form of changed state.
@InjectMocks is the Mockito Annotation. It allows you to mark a field on which an injection is to be performed. Injection allows you to, Enable shorthand mock and spy injections. Minimize repetitive mock and spy injection.
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With