3

我想我没有verify正确使用。这是测试:

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

这是它调用的代码:

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

故障跟踪:

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)

我要验证的电话是几层。有没有不同的方法来检查这个?

4

2 回答 2

0

我不确定你在做什么。给定以下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
    }
}

以及以下GameMaster课程:

public class GameMaster {
    public GameMaster() {
    }

    public void bar() {
    }
}

我会写这样的测试Player

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
    }
}
于 2009-12-28T00:33:14.663 回答
0

您的测试方法中有一个错误:它缺少对GameMaster#canTakeDump(). true当从被测方法调用时,该方法需要返回(因为它if在第 45 行的该语句中使用)。

于 2009-12-28T12:19:57.913 回答