Mockito.anyInt()
works via side-effects; when it passes the value to a real class, it essentially sends 0.
It looks like metadataDao.getStuff
is returning a real LinkedList
, with size 0. Then, you send what amounts to 0
to that real LinkedList
, which calls the real get
method with size 0, and you get the normal error you expect.
You can avoid problems like this by not ever using chained method calls inside Mockito, in other words, never do:
when(obj.methodOne().methodTwo())
Instead, just use one method call. In your example, this might be:
List<MyObj> mockList = Mockito.mock(List.class);
Mockito.when(metadataDao.getStuff(Mockito.anyInt()).thenReturn(mockList);
Mockito.when(mockList.get(Mockito.anyInt())).thenReturn(returnedVariable);
Also note that, as @JeffBowman points out in the comments, you should never be mocking List
when a real List
will do.