我写了这个测试:
@Test
public void testDistance() {
World world = mock(World.class);
AbstractWarp warp = mock(AbstractWarp.class);
Location loc = new Location(world, 0, 0, 0);
when(warp.getLocation()).thenReturn(loc);
Player player = mock(Player.class);
Location loc2 = new Location(world, 100, 0, 0);
when(player.getLocation()).thenReturn(loc2);
double expected = 100;
double actual = warp.distance(player);
verify(player).getLocation();
verify(warp).getLocation();
assertEquals(expected, loc.distance(loc2), .1);
assertEquals(expected, actual, .1);
}
对于AbstractWarp类中的此方法:
public double distance(Player player) {
return player.getLocation().distance(getLocation());
}
我无法弄清楚为什么第一次验证失败并带有以下痕迹:
Wanted but not invoked:
player.getLocation();
-> at paperwarp.domain.AbstractWarpTest.testDistance(AbstractWarpTest.java:36)
Actually, there were zero interactions with this mock.
我做错了什么?
答案 0 :(得分:1)
你做错了是你为AbstractWarp创建了一个模拟器,因此永远不会调用AbstractWarp.distance
的实际实现。
AbstractWarp
所需要的是spy
而不是mock
,如下所示:
AbstractWarp warp = spy(new AbstractWarp()); //instead of new AbstractWarp() use whatever other initialization is appropriate
doReturn(loc).when(warp).getLocation();
请注意,如果您实际上没有打电话给AbstractWarp.getLocation
,那么spy
根本不需要AbstractWarp
。普通班级会做得很好