Java mockito';那就回来吧

Java mockito';那就回来吧,java,list,junit,mockito,enumeration,Java,List,Junit,Mockito,Enumeration,有没有办法在mockito的thenReturn函数中枚举列表中的项目,以便我返回列表中的每个项目。到目前为止,我已经做到了: List<Foo> returns = new ArrayList<Foo>(); //populate returns list Mockito.when( /* some function is called */ ).thenReturn(returns.get(0), returns.get(1), returns.get(2), re

有没有办法在mockito的thenReturn函数中枚举列表中的项目,以便我返回列表中的每个项目。到目前为止,我已经做到了:

List<Foo> returns = new ArrayList<Foo>();
//populate returns list

Mockito.when( /* some function is called */ ).thenReturn(returns.get(0), returns.get(1), returns.get(2), returns.get(3));
我也试过这个:

Mockito.when(service.findFinancialInstrumentById(eq(1L))).thenReturn(
    for (int i=0; i<returns.size(); i++) {
        returns.get(i);
    }
);
Mockito.when(service.findFinancialInstrumentById(eq(1L))。然后返回(
对于(int i=0;ithenReturn()方法签名为

thenReturn(T value, T... values)
它以T为例,后跟一个vararg T…,这是数组的语法糖

when(foo.bar()).thenReturn(list.get(0), 
                           list.subList(1, list.size()).toArray(new Foo[]{}));
但是一个更简洁的解决方案是创建一个应答实现,该实现将列表作为参数,并在每次使用时应答列表的下一个元素,然后使用

when(foo.bar()).thenAnswer(new SequenceAnswer<>(list));
when(foo.bar()).thenAnswer(newsequenceAnswer(list));
例如:

private static class SequenceAnswer<T> implements Answer<T> {

    private Iterator<T> resultIterator;

    // the last element is always returned once the iterator is exhausted, as with thenReturn()
    private T last;

    public SequenceAnswer(List<T> results) {
        this.resultIterator = results.iterator();
        this.last = results.get(results.size() - 1);
    }

    @Override
    public T answer(InvocationOnMock invocation) throws Throwable {
        if (resultIterator.hasNext()) {
            return resultIterator.next();
        }
        return last;
    }
}
私有静态类SequenceAnswer实现Answer{
私有迭代器结果生成器;
//迭代器耗尽后,始终返回最后一个元素,如thenReturn()
私家车最后一辆;
公开答案(列出结果){
this.resultIterator=results.iterator();
this.last=results.get(results.size()-1);
}
@凌驾
公共T应答(调用锁调用)抛出可丢弃{
if(resultIterator.hasNext()){
返回resultIterator.next();
}
最后返回;
}
}
另一种方法(但我个人更喜欢JB Nizet SequenceAnswer的想法)是这样的

OngoingStubbing stubbing = Mockito.when(...);
for(Object obj : list) {
    stubbing = stubbing.thenReturn(obj);
}

那么SequenceAnswer到底是如何实现的呢?只是一个外部类?我对mockito和junit测试非常陌生,所以所有这些对我来说都是全新的。我不需要实际实现,只要参考一个示例就可以了。我个人还是会做你的解决方案,JB,但谢谢;-)实际上,这个解决方案已经不起作用了。它会产生
org.mockito.exceptions.misusing.unfinishedstubingexception
。但是,
thenAnswer()
解决方案会产生异常,即使是匿名内部类或lambda。
OngoingStubbing stubbing = Mockito.when(...);
for(Object obj : list) {
    stubbing = stubbing.thenReturn(obj);
}