java - 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));
}
解决方案
Mockito 间谍将调用委托给实际的底层对象。即使在存根时也是如此。所以 :
when(list.get(0)).thenReturn("abc");
已经对间谍进行了调用。
new ArrayList()
是一个空列表。即使在存根期间调用list.get(0)
它,也会导致IndexOutOfBoundsException
.
当您在类上使用间谍时,没有实际的实例可以委托给,并且作为List
没有实现的接口get()
,Mockito 不会委托给任何“实际代码”。
所以,失败的是存根。
不过,有一个简单的解决方案。通过使用doReturn()
存根的风格,您可以避免在存根期间进行实际调用,代价是阅读不太流畅。
doReturn("abc").when(list).get(0);
推荐阅读
- javascript - ReactJS隐藏地图功能的第一个孩子
- javascript - Firebase 云功能 onCreate 没有运行?
- android - 使用 Glide 旋转屏幕 android 设备时图像模糊
- php - 从另一个 php 文件运行 php 文件,就好像我直接从浏览器打开它一样(相对路径问题)
- multithreading - 使用 ref 类形式 c++ 中的线程进行并行工作
- python - 扫雷:显示周围的块功能冻结
- php - PHP / MYSQL:使用编码base64将图像上传到数据库
- javascript - 匹配或不匹配所有投影结果 - Mongodb
- reactjs - 反应状态变化
- python - 撞到块后如何固定我的角色位置?