gpt4 book ai didi

java - jMock 不顾期望失败

转载 作者:太空宇宙 更新时间:2023-11-04 06:56:23 24 4
gpt4 key购买 nike

我目前正在尝试做一个垄断游戏的模拟测试课。

我们已经得到了一些关于如何设置其中一些的说明,但也许我们只是误解了 JMock 的工作原理。

我们有使用 takeTurn() 的 Player 类。我们有 DieBoardPiece 这些都是支持模拟的接口(interface)。然后我们有 Square 类,它不包含任何值,但仅代表一个 Square。也许我们应该把它变成一个接口(interface),因为它什么也没有,但我不知道。

无论我们做什么,测试总是失败。我尝试省略某些部分,以便我们也只执行一个期望,但没有运气。我们是否完全误解了 JMock?

这是我们的 Player 类:

public class Player {

Die d;
Piece p;
Board b;

void takeTurn(Die d, Piece p, Board b) {
this.d = d;
this.p = p;
this.b = b;

int i = d.roll();
int v = d.roll();

Square newLoc = b.getSquare(p.getLocation(), i + v);
p.setLocation(newLoc);
}
}

这是我们的 PlayerTest 类:

public class PlayerTest extends TestCase {

Mockery context = new Mockery();


public void testTakeTurn() {
final Board b = context.mock(Board.class);
final Piece p = context.mock(Piece.class);
final Die d = context.mock(Die.class);

Player pl = new Player();

context.checking(new Expectations() {{
exactly(2).of (d).roll();
}});

context.checking(new Expectations() {{
oneOf (p).getLocation();
}});

final int diceroll = 5;

context.checking(new Expectations() {{
oneOf (b).getSquare(p.getLocation(), diceroll);
}});

final Square newLoc = new Square();

context.checking(new Expectations() {{
oneOf (p).setLocation(newLoc);
}});

pl.takeTurn(d,p,b);

context.assertIsSatisfied();
}
}

最佳答案

模拟背后的想法是你生成可​​以设定期望的假对象。期望包括将调用哪些方法以及这些方法将返回哪些结果。

后一个任务是您在当前代码中遗漏的。您需要告诉 JMock 模拟对象上的方法调用将返回什么值。如果没有告诉 JMock,它默认为 null0false 等值。

例如,您声明希望掷两次骰子,但没有提供模拟的 Dice 对象应返回的返回值。所以 JMock 将只返回 0。稍后您假设这两个骰子的总和为 5,这是错误的。

您的代码应更改为大致如下(未经测试):

public class PlayerTest extends TestCase {

Mockery context = new Mockery();

public void testTakeTurn() {
final Board b = context.mock(Board.class);
final Piece p = context.mock(Piece.class);
final Die d = context.mock(Die.class);

Player pl = new Player();
final int roll1 = 2;
final int roll2 = 3;

context.checking(new Expectations() {{
exactly(2).of (d).roll();
will(onConsecutiveCalls(
returnValue(roll1),
returnValue(roll2))
}});

final Location currentLocation = // set to your desired test loc...

context.checking(new Expectations() {{
oneOf (p).getLocation();
will(returnValue(currentLocation));
}});

final Square newLoc = new Square();

context.checking(new Expectations() {{
oneOf (b).getSquare(currentLocation, roll1 + roll2);
will(returnValue(newLoc));
}});


context.checking(new Expectations() {{
oneOf (p).setLocation(newLoc);
}});

pl.takeTurn(d,p,b);

context.assertIsSatisfied();
}
}

尽管我曾经很喜欢 JMock,但我必须同意 Mockito 使用起来更加友好的评论。如果您刚刚开始模拟,现在可能是切换的好时机。

关于java - jMock 不顾期望失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22686647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com