Expanding David's answer whom I totally agree with that you should create a wrapper for Random. I wrote pretty much the same answer about it earlier in a similar question so here is a "Cliff's notes version" of it.
What you should do is to first create the wrapper as an interface (or abstract class):
public interface IRandomWrapper {
int getInt();
}
And the concrete class for this would look like this:
public RandomWrapper implements IRandomWrapper {
private Random random;
public RandomWrapper() {
random = new Random();
}
public int getInt() {
return random.nextInt(10);
}
}
Say your class is the following:
class MyClass {
public void doSomething() {
int i=new Random().nextInt(10)
switch(i)
{
//11 case statements
}
}
}
In order to use the IRandomWrapper correctly you need to modify your class to take it as a member (through constructor or a setter):
public class MyClass {
private IRandomWrapper random = new RandomWrapper(); // default implementation
public setRandomWrapper(IRandomWrapper random) {
this.random = random;
}
public void doSomething() {
int i = random.getInt();
switch(i)
{
//11 case statements
}
}
}
You can now test your class's behaviour with the wrapper, by mocking the wrapper. You can do this with a mocking framework, but this is easy to do by yourself as well:
public class MockedRandomWrapper implements IRandomWrapper {
private int theInt;
public MockedRandomWrapper(int theInt) {
this.theInt = theInt;
}
public int getInt() {
return theInt;
}
}
Since your class expects something that looks like an IRandomWrapper
you can now use the mocked one to force the behaviour in your test. Here are some examples of JUnit tests:
@Test
public void testFirstSwitchStatement() {
MyClass mc = new MyClass();
IRandomWrapper random = new MockedRandomWrapper(0);
mc.setRandomWrapper(random);
mc.doSomething();
// verify the behaviour for when random spits out zero
}
@Test
public void testFirstSwitchStatement() {
MyClass mc = new MyClass();
IRandomWrapper random = new MockedRandomWrapper(1);
mc.setRandomWrapper(random);
mc.doSomething();
// verify the behaviour for when random spits out one
}
Hope this helps.