}
@Test
public void testUpdateNotFind() throws Exception {
boolean result = personService.update(2, “new name”);
assertFalse(“must true”, result);
//验证是否执行过一次getPerson(1)
verify(mockDao, times(1)).getPerson(eq(1));
//验证是否执行过一次update
verify(mockDao, never()).update(isA(Person.class));
}
}
Mockito使用示例
===========
模拟对象
// 模拟LinkedList 的一个对象
LinkedList mockedList = mock(LinkedList.class);
// 此时调用get方法,会返回null,因为还没有对方法调用的返回值做模拟
System.out.println(mockedList.get(0));
模拟方法调用的返回值
// 模拟获取第一个元素时,返回字符串first。 给特定的方法调用返回固定值在官方说法中称为stub。
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(“clear exception”)).when(mockedList).clear();
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”);
校验行为
// mock creation
List mockedList = mock(List.class);
// using mock object
mockedList.add(“one”);
mockedList.clear();
//verification