Home > OS >  Unit Testing for a random number
Unit Testing for a random number

Time:02-21

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

CodePudding user response:

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...

  • Related