0

My dice game has a method rollAllDice() which is called when all the dice are rolled by a player. This inturn will call clearAllDiceSelections() method for deselecting the previous selection of all dice. Now I need to write test case for whether the dice were deselected or not ??

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;
}
Karthik Cherukuri
  • 603
  • 2
  • 9
  • 15
  • Unfortunately your `clearAllDiceSelections()` is `private`; if you could afford to make it package local for instance then you could use mockito and `spy()` on it, which would allow you to perform the invocation check. As an aside, please stick to Java naming conventions. – fge Mar 01 '15 at 14:15

3 Answers3

2

In general, you should not test your private methods, look Should I test private methods or only public ones?. Covering your public method cases will be enough. Testing private methods breaks encapsulation.

If you think that the private method have to be tested, then something wrong in your code design. You should rethink your code implementation.

Community
  • 1
  • 1
Vassilis Blazos
  • 1,560
  • 1
  • 14
  • 20
0

You could do it so if you have access to f_faceValue and f_dice. You could assert on like

for (Die d: f_dice) {
    assertFalse(d.getSelected());
}
SMA
  • 36,381
  • 8
  • 49
  • 73
0

Your method is private, so unfortunately there is no "ready way" to test that short of using a "power mock" framework.

What you can do is make this method package private instead; Guava has a very convenient annotation for this (which you can easily recreate):

@VisibleForTesting
void clearAllDiceSelections()
{
    // etc
}

Provided you have that you could then use mockito to write a test like this:

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

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

dice.rollAllDice();

verify(dice).clearAllDiceSelections();
fge
  • 119,121
  • 33
  • 254
  • 329