简体   繁体   English

Mockito.spy(List.class) 和 Mockito.spy(new ArrayList()) 有什么区别?

[英]What is difference between Mockito.spy(List.class) and Mockito.spy(new ArrayList())?

The first test case is failed due to IndexOutOfBoundsException.由于 IndexOutOfBoundsException,第一个测试用例失败。 The second one is successful.第二个成功了。 What is difference between Mockito.spy(List.class) and Mockito.spy(new ArrayList())? 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));
}

Mockito spies delegate calls to the actual underlying object. Mockito 间谍将调用委托给实际的底层对象。 This is true even when stubbing.即使在存根时也是如此。 So :所以 :

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

already does an invocation on the spy.已经对间谍进行了调用。

new ArrayList() is an empty list. new ArrayList()是一个空列表。 Calling list.get(0) on it, even during stubbing, will result in a IndexOutOfBoundsException .对其调用list.get(0) ,即使在存根期间,也会导致IndexOutOfBoundsException

When you use a spy on a class, there is no actual instance to delegate to, and as List is an interface with no implementation for get() , Mockito will not delegate to any 'actual code'.当您在类上使用间谍时,没有实际的实例可以委托给,并且由于List是一个没有实现get()的接口,Mockito 不会委托给任何“实际代码”。

So, it's the stubbing that fails.所以,这是失败的存根。

There is an easy solution, though.不过,有一个简单的解决方案。 By using the doReturn() style of stubbing you avoid actual invocations during stubbing, at the expense of reading a little less fluently.通过使用doReturn()风格的存根,您可以在存根期间避免实际调用,代价是阅读不太流畅。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM