JCS
JCS

Reputation: 13

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

Upvotes: 0

Views: 836

Answers (1)

Győző Nyári
Győző Nyári

Reputation: 54

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

Upvotes: 1

Related Questions