使用Mockito测试Java增强的行为

使用Mockito测试Java增强的行为,第1张

使用Mockito测试Java增强的行为

模拟迭代器对我有用参见下面的代码示例

import static org.junit.Assert.assertEquals;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;import java.util.Collection;import java.util.Iterator;import org.junit.Before;import org.junit.Test;public class TestMockedIterator {    private Collection<String> fruits;    private Iterator<String> fruitIterator;    @SuppressWarnings("unchecked")    @Before    public void setUp() {        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);    }    @Test    public void test() {        int iterations = 0;        for (String fruit : fruits) { iterations++;        }        assertEquals(3, iterations);    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5616153.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存