首页 > 解决方案 > Mockito.spy(List.class) 和 Mockito.spy(new ArrayList()) 有什么区别?

问题描述

由于 IndexOutOfBoundsException,第一个测试用例失败。第二个是成功的。Mockito.spy(List.class) 和 Mockito.spy(new ArrayList()) 有什么区别?

@Test
public void thenReturnWithSpy1() {

    List<String> list = Mockito.spy(List.class);

    when(list.get(0)).thenReturn("abc");

    assertEquals("abc", list.get(0));
}

@Test
public void thenReturnWithSpy2() {

    List<String> list = Mockito.spy(new ArrayList());

    when(list.get(0)).thenReturn("abc");

    assertEquals("abc", list.get(0));
}

标签: javajunitmockito

解决方案


Mockito 间谍将调用委托给实际的底层对象。即使在存根时也是如此。所以 :

when(list.get(0)).thenReturn("abc");

已经对间谍进行了调用。

new ArrayList()是一个空列表。即使在存根期间调用list.get(0)它,也会导致IndexOutOfBoundsException.

当您在类上使用间谍时,没有实际的实例可以委托给,并且作为List没有实现的接口get(),Mockito 不会委托给任何“实际代码”。

所以,失败的是存根。

不过,有一个简单的解决方案。通过使用doReturn()存根的风格,您可以避免在存根期间进行实际调用,代价是阅读不太流畅。

doReturn("abc").when(list).get(0);

推荐阅读