Mockito的thenReturn中的Java枚举列表 [英] Java Enumerating list in mockito's thenReturn

查看:441
本文介绍了Mockito的thenReturn中的Java枚举列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以枚举Mockito的thenReturn函数中列表中的项目,所以我可以返回列表中的每个项目.到目前为止,我已经做到了:

Is there a way to enumerate the items in a list within mockito's thenReturn function so I return each item in a list. So far I've done this:

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));

这完全符合我的要求.每次调用该函数时,它都会从列表中返回一个不同的对象,例如get(1)get(2)等.

This works exactly how I want it to. Each time the function is called, it returns a different object from the list, e.g get(1), get(2) etc.

但是我想简化此过程,使其对任何尺寸的列表都更加动态,以防万一我有一个尺寸为100的列表.

But I want to simplify this and make it more dynamic to any size list in case I have a list with size say 100. I tried something like this:

Mockito.when( /* some function is called */ ).thenReturn(
    for(Foo foo : returns) {
        return foo;
    }
);

我也尝试过:

Mockito.when(service.findFinancialInstrumentById(eq(1L))).thenReturn(
    for (int i=0; i<returns.size(); i++) {
        returns.get(i);
    }
);

但是这不起作用....所以我如何在thenReturn中枚举此列表....我遇到了其他方法来喜欢thenanswer,但是我不是确保哪种方案在这种情况下效果最好.

But this doesn't work....so how do I enumerate this list within the thenReturn....I've come across other methods to like then or answerbut I'm not sure which one works best in this scenario.

推荐答案

另一种实现方法(但就我个人而言,我更喜欢JB Nizet SequenceAnswer的想法),将是这样的……

Another way of doing it (but personally, I prefer JB Nizet SequenceAnswer idea), would be something like this...

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

这篇关于Mockito的thenReturn中的Java枚举列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆