[英]How to test with JUnit through a test case whether a method is executed in another method?
我的骰子游戏有一个rollAllDice()方法,当所有骰子都由玩家掷出时会被调用。 这将调用clearAllDiceSelections()方法来取消选择所有骰子的先前选择。 现在,我需要编写测试用例,以检查是否取消选择了骰子?
public void rollAllDice() {
clearAllDiceSelections();
for (Die d: f_dice) {
d.roll();
}
}
private void clearAllDiceSelections() {
for (Die d: f_dice) {
d.setSelected(false);
}
}
public void roll() {
f_faceValue = f_randgen.nextInt(f_sides) + 1;
}
通常,您不应该测试私有方法,而是应该测试私有方法还是仅测试公共方法? 。 涵盖您的公共方法案例就足够了。 测试私有方法会破坏封装。
如果您认为必须测试私有方法,则代码设计中有问题。 您应该重新考虑您的代码实现。
如果可以访问f_faceValue和f_dice,则可以这样做。 你可以断言像
for (Die d: f_dice) {
assertFalse(d.getSelected());
}
您的方法是private
,因此不幸的是,除了使用“电源模拟”框架之外,没有“准备好的方法”来进行测试。
您可以做的是将此方法包设置为私有。 番石榴对此有一个非常方便的注释(您可以轻松地重新创建):
@VisibleForTesting
void clearAllDiceSelections()
{
// etc
}
如果您有,则可以使用mockito编写如下测试:
final Dice dice = spy(new Dice());
doNothing().when(dice).clearAllDiceSelections();
dice.rollAllDice();
verify(dice).clearAllDiceSelections();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.