gpt4 book ai didi

mockito - 模拟连续调用的不同响应

转载 作者:行者123 更新时间:2023-12-05 07:21:19 25 4
gpt4 key购买 nike

我正在测试过滤器方法,该方法将列表作为输入并为列表中的每个项目调用另一个方法(返回 bool 值),并计算符合条件的项目数。

Mockito.doReturn(valid)
.doReturn(inValid)
.doReturn(valid)
.doReturn(inValid)
.doReturn(valid)
.when(mySpy).isEligible(
any(Item.class),anyString());

这曾经在要测试的方法在 for 循环中调用 isEligible 时起作用

public int filter(List<Item> items){
int count=0;
for(i=0;i<items.size;i++){
if(isEligible(items.get(i)))
count++;
return count;
}

现在我把它改为使用java流

public int filter(List<Item> items){
items.stream().filter(item -> isEligible(item));
return items.size;
}

现在我的模拟不工作了,正在调用真正的方法

最佳答案

Stubbing consecutive calls (iterator-style stubbing)使用 thenReturn 进行连续 stub

Sometimes we need to stub with different return value/exception for the same method call. Typical use case could be mocking iterators. Original version of Mockito did not have this feature to promote simple mocking. For example, instead of iterators one could use Iterable or simply collections. Those offer natural ways of stubbing (e.g. using real collections). In rare scenarios stubbing consecutive calls could be useful, though:

 when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");

//First call: throws runtime exception:
mock.someMethod("some arg");

//Second call: prints "foo"
System.out.println(mock.someMethod("some arg"));

//Any consecutive call: prints "foo" as well (last stubbing wins).
System.out.println(mock.someMethod("some arg"));

替代的、较短版本的连续 stub :

when(mock.someMethod("some arg"))
.thenReturn("one", "two", "three");

在你的情况下

Mockito.mock(mySpy.isEligible(any(Item.class))).thenReturn(true,false,false,true);

关于mockito - 模拟连续调用的不同响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56965987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com