Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock the return value of a Map?

Tags:

java

mockito

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!

like image 200
CNDyson Avatar asked Apr 04 '13 19:04

CNDyson


People also ask

How to mock a function with Mockito?

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.

What is InjectMocks?

@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.

Can I mock private methods using Mockito?

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.


1 Answers

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.

like image 174
codebox Avatar answered Sep 16 '22 14:09

codebox