Elementvin 2010-08-27
更多信息请参考如下位置,
原文链接:http://www.infoq.com/cn/news/2008/09/mockito-1.5
官方网站:http://code.google.com/p/mockito/
以下内容均参考至http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html。
import static org.mockito.Mockito.*;
// 模拟LinkedList 的对象 LinkedList mockedList = mock(LinkedList.class); // 此时调用get方法,是会返回null,因为还没有对方法调用的返回值做模拟 System.out.println(mockedList.get(999));
模拟方法调用的返回值
// 模拟获取第一个元素时,返回字符串first
when(mockedList.get(0)).thenReturn("first");
// 此时打印输出first
System.out.println(mockedList.get(0)); // 模拟获取第二个元素时,抛出RuntimeException when(mockedList.get(1)).thenThrow(new RuntimeException()); // 此时将会抛出RuntimeException System.out.println(mockedList.get(1));
doThrow(new RuntimeException()).when(mockedList).clear();
// anyInt()匹配任何int参数,这意味着参数为任意值,其返回值均是element
when(mockedList.get(anyInt())).thenReturn("element");
// 此时打印是element
System.out.println(mockedList.get(999)); // 调用add一次
mockedList.add("once");
// 下面两个写法验证效果一样,均验证add方法是否被调用了一次
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");