简体   繁体   中英

Mockito When().thenReturn returning an Iterator

I am trying to return an iterator from when().theReturn but I keep getting this error:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Itr cannot be returned by findAll()
findAll() should return List

This what I'm trying to do:

List<Client> iterList = mockClientList1.findAll();
final Iterator<Client> iter = newMockListClient.iterator();
when(iterList.iterator()).thenReturn(iter);

mockClientList1 is an object ClientList and findAll() is a method that returns a list of Client. I saw a post regarding a limitation of Mockito about stacking methods on when.thenReturn but I'm not sure if that is the reason why this is failing? Any tips would be very much appreciated.

If you want to do it like that, you need to provide a stub for the return value of findAll() too.

List<Client> mockList = mock(List.class)
when(mockClientList1.findAll()).thenReturn(mockList);
final Iterator<Client> iter = newMockListClient.iterator();
when(mockList.iterator()).thenReturn(iter);

But unless there's a specific reason you want to stub only the iterator, you can also return the list directly:

when(mockClientList1.findAll()).thenReturn(mockListClient);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM