简体   繁体   中英

How do I create a unit test for a constructor with Random class in java

Here is my constructor

    public Dice(final int numOfDice)
    {   
        if(numOfDice < Skunk.LOWEST_NUM_OF_DICE && numOfDice > Skunk.HIGHEST_NUM_OF_DICE)
        {
            throw new IllegalArgumentException("the number of dice must be " + Skunk.LOWEST_NUM_OF_DICE + " or " + Skunk.HIGHEST_NUM_OF_DICE);
        }
        
        this.numOfDice = numOfDice;
        
        dice = new int[this.numOfDice];
        
        Random  r;
        r = new Random();
                
        for(int i=0; i<this.numOfDice; i++)
        {
            dice[i] = r.nextInt(HIGHEST_NUMBER_ON_DIE-LOWEST_NUMBER_ON_DIE+OFFSET) + LOWEST_NUMBER_ON_DIE;
        }
    }

I want to be able to write a unit test where I initialize the dice to specific values. However, I can't seem to figure out how I can control the Random class. I tried @Override on the constructor but it only works for functions. I tried moving the for loop to a method called roll and using @Override on it but @Override doesn't work on functions called in the constructor.

I have installed Mockito and am trying to follow the advice posted in the first answer here: How to test a method that uses Random(), without arguments and return value, using JUnit or Mockito But I don't know how Mockito works.

Make the Random object a field and mock it:

private Random random = new Random();

public Dice(final int numOfDice)
{   
    if(numOfDice < Skunk.LOWEST_NUM_OF_DICE && numOfDice > Skunk.HIGHEST_NUM_OF_DICE)
    {
        throw new IllegalArgumentException("the number of dice must be " + Skunk.LOWEST_NUM_OF_DICE + " or " + Skunk.HIGHEST_NUM_OF_DICE);
    }
    
    this.numOfDice = numOfDice;
    
    dice = new int[this.numOfDice];
    for(int i=0; i<this.numOfDice; i++)
    {
        dice[i] = random.nextInt(HIGHEST_NUMBER_ON_DIE-LOWEST_NUMBER_ON_DIE+OFFSET) + LOWEST_NUMBER_ON_DIE;
    }
}

Replace random with a mock for your tests.

I am not sure why do need to test the outcomes of Random, the main intention should be to test whether your dice[] has the value between the specified range or not.

I would suggest you to call the method and read all the values inside dice[] and check if each value is present inside your specified range,

Range: 0 to ((HIGHEST_NUMBER_ON_DIE-LOWEST_NUMBER_ON_DIE+OFFSET) + LOWEST_NUMBER_ON_DIE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM