Search code examples
javaunit-testingjunitjunit4

Unit Testing for a random number


I am trying to create a junit test on a random number generator. However, I am not sure how you do this.

package main;
import java.util.Random;
    
public class Dice {
    public int DiceRoll() {
        Random rand = new Random();
        return rand.nextInt(6)+1;
    }
}

Solution

  • Implement the Dice class like this:

    public Dice {
    
        private Random random;
    
        public Dice(Random random) {
            this.random = random;
        }
    }
    

    Then in the test you can inject a mock, which can return a predefined value...