我想测试一个使用Mockito对其进行增强的
java方法.问题是当我不知道如何设定增强工作的期望.以下代码从
an unanswered question in the mockito google group获得:
import static org.mockito.Mockito.when; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.mockito.Mockito; import org.testng.annotations.Test; public class ListTest { @Test public void test() { List<String> mockList = Mockito.mock(List.class); Iterator<String> mockIterator = Mockito.mock(Iterator.class); when(mockList.iterator()).thenReturn(mockIter); when(mockIter.hasNext()).thenReturn(true).thenReturn(false); when(mockIter.next()).thenReturn("A"); boolean flag = false; for(String s : mockList) { flag = true; } assertTrue(flag); } }
for循环中的代码不会被执行.设置迭代器的期望不起作用,因为java enhanced for不在内部使用list iterator.设置List.get()方法的期望不是因为增强的实现似乎也不调用列表的get()方法.
任何帮助将不胜感激.
解决方法
模拟迭代器为我工作.见下面的代码示例:
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,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); } }