Java:可能使用 Mockito 进行模拟测试
我认为我没有正确使用 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)
我要验证的调用位于几层以下。有其他方法可以检查吗?
I think I'm not using verify
correctly. Here is the test:
@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
}
Here is the code it calls:
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;
}
Failure trace:
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)
The call I want to verify is several layers down. Is there a different way to check this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的测试方法存在错误:缺少
GameMaster#canTakeDump()
的必要期望。当从测试方法调用时,此方法需要返回 true(因为它在第 45 行的 if 语句中使用)。There is an error in your test method: it's missing a necessary expectation for the
GameMaster#canTakeDump()
. This method needs to returntrue
when called from the tested method (because of its use in thatif
statement at line 45).我不确定你在做什么。给定以下
Player
类:和以下
GameMaster
类:我会像这样编写
Player
的测试:I'm not sure to understand what you are doing. Given the following
Player
class:And the following
GameMaster
class:I'd write the test of
Player
like this: