gpt4 book ai didi

java - 如何使用 Mockito 模拟 forEach 行为

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:01:41 26 4
gpt4 key购买 nike

我想完成以下工作,但我不知道如何正确模拟 forEach 行为。 (代码摘自一个相关问题Testing Java enhanced for behavior with Mockito)

@Test
public void aa() {
Collection<String> fruits;
Iterator<String> fruitIterator;

fruitIterator = mock(Iterator.class);
when(fruitIterator.hasNext()).thenReturn(true, true, true, false);
when(fruitIterator.next()).thenReturn("Apple")
.thenReturn("Banana").thenReturn("Pear");

fruits = mock(Collection.class);
when(fruits.iterator()).thenReturn(fruitIterator);
doCallRealMethod().when(fruits).forEach(any(Consumer.class));

// this doesn't work (it doesn't print anything)
fruits.forEach(f -> {
mockObject.someMethod(f);
});

// this works fine
/*
int iterations = 0;
for (String fruit : fruits) {
mockObject.someMethod(f);
}
*/

// I want to verify something like this
verify(mockObject, times(3)).someMethod(anyString());
}

任何帮助将不胜感激。

最佳答案

Iterator mockIterator = mock(Iterator.class);
doCallRealMethod().when(fruits).forEach(any(Consumer.class));
when(fruits.iterator()).thenReturn(mockIterator);
when(mockIterator.hasNext()).thenReturn(true, false);
when(mockIterator.next()).thenReturn(mockObject);

关于java - 如何使用 Mockito 模拟 forEach 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49406075/

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