英文:
Mockito When().thenReturn returning an Iterator
问题
我试图从when().theReturn
返回一个迭代器,但我一直在得到这个错误:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
findAll() 不能返回 Itr
findAll() 应该返回 List
这是我正在尝试做的事情:
List<Client> iterList = mockClientList1.findAll();
final Iterator<Client> iter = newMockListClient.iterator();
when(iterList.iterator()).thenReturn(iter);
mockClientList1
是一个 ClientList
对象,findAll()
是一个返回 Client
列表的方法。我看到过一个关于 Mockito 限制的帖子,关于在 when.thenReturn
上叠加方法的问题,但我不确定是否这就是失败的原因?任何提示将不胜感激。
英文:
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.
答案1
得分: 2
如果你想这样做,你还需要为findAll()
的返回值提供一个存根。
List<Client> mockList = mock(List.class);
when(mockClientList1.findAll()).thenReturn(mockList);
final Iterator<Client> iter = newMockListClient.iterator();
when(mockList.iterator()).thenReturn(iter);
但是,除非你有特定的原因只想要存根迭代器,你也可以直接返回列表:
when(mockClientList1.findAll()).thenReturn(mockListClient);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论