在任何应用Mockito的地方,加上如下片段:
import static org.mockito.Mockito.*;
模拟对象
1. // 模拟LinkedList 的对象
2. LinkedList mockedList = mock(LinkedList.class);
模拟方法调用的返回值
1. // 模拟获取第一个元素时,返回字符串first
2. when(mockedList.get(0)).thenReturn("first");
4. // 此时打印输出first
5. System.out.println(mockedList.get(0));
模拟方法调用抛出异常
1. // 模拟获取第二个元素时,抛出RuntimeException
2. when(mockedList.get(1)).thenThrow(new RuntimeException());
4. // 此时将会抛出RuntimeException
5. System.out.println(mockedList.get(1));
没有返回值类型的方法也可以模拟异常抛出:
1. doThrow(new RuntimeException()).when(mockedList).clear();
模拟方法调用的参数匹配
1. // anyInt()匹配任何int参数,这意味着参数为任意值,其返回值均是element
2. when(mockedList.get(anyInt())).thenReturn("element");
4. // 此时打印是element
5. System.out.println(mockedList.get(999));
更灵活的参数匹配,请参见http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Matchers.html
验证方法调用次数
1. // 调用add一次
2. mockedList.add("once");
3.
4. // 下面两个写法验证效果一样,均验证add方法是否被调用了一次
5. verify(mockedList).add("once");
6. verify(mockedList, times(1)).add("once");
还可以通过atLeast(int i)和atMost(int i)来替代time(int i)来验证被调用的次数最小值和最大值。