Mockito的`when().thenReturn`返回一个Iterator。

huangapple go评论113阅读模式
英文:

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&lt;Client&gt; iterList = mockClientList1.findAll();
final Iterator&lt;Client&gt; 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&lt;Client&gt; mockList = mock(List.class)
when(mockClientList1.findAll()).thenReturn(mockList);
final Iterator&lt;Client&gt; 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);

huangapple
  • 本文由 发表于 2020年4月8日 21:36:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/61102016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定