Question

I wrote this test:

@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);
}

for this method in the AbstractWarp class:

public double distance(Player player) {
    return player.getLocation().distance(getLocation());
}

And I can't figure out why the first verification fails with the following trace:

Wanted but not invoked:
player.getLocation();
-> at paperwarp.domain.AbstractWarpTest.testDistance(AbstractWarpTest.java:36)
Actually, there were zero interactions with this mock.

What am I doing wrong?

Was it helpful?

Solution

What you are doing wrong is that you have created a mock for AbstractWarp and therefore your actual implementation of AbstractWarp.distance is never being called.

What you need for AbstractWarp is a spy instead of a mock like this:

AbstractWarp warp = spy(new AbstractWarp()); //instead of new AbstractWarp() use whatever other initialization is appropriate
doReturn(loc).when(warp).getLocation();

Note that if you aren't actually going to be calling AbstractWarp.getLocation, you don't need the spy at all for AbstractWarp. A regular class will do just fine

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top