Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a JUnit test for a random number generator

Tags:

java

random

junit

I have a method which returns a random number between 0 and 10.

public int roll(){
    int pinsKnockedDown = (int) (Math.random() * 10);
    return pinsKnockedDown;
}

How would I write a JUnit test for this? So far I have put the call in a loop so it runs 1000 times and fails the test if - the number is less than 0 - the number is more than 10

How can I test that all the numbers aren't just the same, i.e.

Dilbert

like image 240
Carrie Hall Avatar asked Feb 11 '13 11:02

Carrie Hall


People also ask

How do you generate a random number between 1 to 10 in Java?

For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);

How do you make a JUnit test?

To use JUnit you must create a separate . java file in your project that will test one of your existing classes. In the Package Explorer area on the left side of the Eclipse window, right-click the class you want to test and click New → JUnit Test Case. A dialog box will pop up to help you create your test case.


1 Answers

Randomness tests are potentially complex. e.g. in the above do you simply want to ensure you get numbers between 1 and 10 ? Do you want to ensure a uniform distribution etc.? At some stage I would suggest you want to trust Math.random() and simply ensure you haven't screwed up the limits/range, which is essentially what you're doing.

like image 160
Brian Agnew Avatar answered Oct 13 '22 01:10

Brian Agnew