Pregunta

Creo que no estoy usando verify correctamente. Aquí está la prueba:

@Mock GameMaster mockGM;    
Player pWithMock;

@Before
public void setUpPlayer() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    pWithMock = new Player(mockGM);
}

@Test
    public void mockDump() {
        pWithMock.testDump();
        verify(mockGM).emitRandom(); // fails
    }

Este es el código que llama:

public boolean testDump() {
    Letter t = tiles.getRandomTile();
    return dump(t);
}

private boolean dump(Letter tile) {
            if (! gm.canTakeDump() || tiles.count() == 0) {
        return false;
    }

    tiles.remove(tile);
    gm.takeTile(tile);
    for (int i = 0; i < 3; i++) {
        tiles.addTile(gm.emitRandom()); // this is the call I want to verify
    }
    return true;
}

Si no dejar rastro:

Wanted but not invoked:
gameMaster.emitRandom();
-> at nth.bananas.test.PlayerTest.mockDump(PlayerTest.java:66)

However, there were other interactions with this mock:
-> at nth.bananas.Player.dump(Player.java:45)

    at nth.bananas.test.PlayerTest.mockDump(PlayerTest.java:66)

La llamada que quiero es para verificar varias capas hacia abajo. ¿Hay una manera diferente para comprobar esto?

¿Fue útil?

Solución

Hay un error en el método de prueba: le falta una expectativa necesaria para la GameMaster#canTakeDump(). Este método necesita a true retorno cuando se llama desde el método probado (debido a su uso en esa declaración if en la línea 45).

Otros consejos

No estoy seguro de entender lo que está haciendo. Dada la siguiente clase Player:

public class Player {
    private final GameMaster gm;

    public Player(GameMaster gameMaster) {
        this.gm = gameMaster;
    }

    public void foo() {
        gm.bar(); // this is the call we want to verify
    }
}

Y la siguiente clase de GameMaster:

public class GameMaster {
    public GameMaster() {
    }

    public void bar() {
    }
}

me gustaría escribir la prueba de Player como esto:

import static org.mockito.Mockito.verify;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class PlayerTest {

    @Mock
    private GameMaster gm;

    @Test
    public void testFoo() {
        Player player = new Player(gm);
        player.foo();
        verify(gm).bar(); // pass
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top