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.
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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With