如何通过测试用例用JUnit测试一个方法是否在另一个方法中执行?

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

一般来说,你不应该测试你的私有方法,看Should I test private methods or only public ones?。涵盖您的 public 方法案例就足够了。测试私有方法会破坏封装。

如果你认为私有方法必须要测试,那么你的代码设计有问题。您应该重新考虑您的代码实现。

您的方法是 private,所以不幸的是没有 "ready way" 来测试缺少 "power mock" 框架。

您可以做的是将此方法封装为私有; Guava 对此有一个非常方便的注释(您可以轻松地重新创建):

@VisibleForTesting
void clearAllDiceSelections()
{
    // etc
}

前提是你可以使用 mockito 编写这样的测试:

final Dice dice = spy(new Dice());

doNothing().when(dice).clearAllDiceSelections();

dice.rollAllDice();

verify(dice).clearAllDiceSelections();