mockito5.4.0单元测试(12) --spy一个真实的对象,使该真实对象可以被mock操作和verify验证

发布时间 2023-06-26 17:23:05作者: 梦幻朵颜

mockito官方文档地址: https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#spy

// new一个真实对象
List list = new LinkedList();
List spy = spy(list); // 把这个真实对象放到spy方法里

//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);   // spy之后,就可以对这个真实对象做一些mock操作了

//using the spy calls *real* methods
spy.add("one");
spy.add("two");

//prints "one" - the first element of a list
System.out.println(spy.get(0));

//size() method was stubbed - 100 is printed
System.out.println(spy.size());

//optionally, you can verify
verify(spy).add("one");   // spy之后,就可以对这个真实对象做verify验证了。
verify(spy).add("two");

 

spy真实对象的一些可能会引起抛出异常的代码:

try {
    //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
    // 因为spy对象此时是真实对象,所以这里的get 0就会直接报索引异常,因为此时spy作为真实的list对象,还是个空集合。
    when(spy.get(0)).thenReturn("foo");
} catch (Exception e) {
    log.error("因为spy对象此时是真实对象,所以这里的get 0就会直接报索引异常", e);
}

//You have to use doReturn() for stubbing
// 如果你非要使spy真实对象返回一个mock值,你只能使用这种方式
doReturn("foo").when(spy).get(0);
log.info("这个log会正常打印的,spy.get(0)::: {}", spy.get(0));

 

 

end.