I am trying to test a method which uses Random.nextDouble(). I need to set what this number will be to test the outcome of the method. I am unable to mock the random class. Here is the error message:
Mockito cannot mock this class: class java.util.Random.
Mockito can only mock non-private & non-final classes.
Here is a rough idea of what I am trying to do:
public string foo() {
Random random = new Random();
String word;
if(random.nextDouble() <= 0.5) {
word += "Hello";
}
if(random.nextDouble() <= 0.7) {
word += "World";
}
return word;
}
And then the test class should look like this:
public class FooTest {
@Test
public void test {
Mockito.mock(Random.class);
when(random.nextDouble()).thenReturn(0.6);
// Basically check that foo() returns "World" because the random number is 0.6
Assertions.assertEquals("World", foo())
}
}
Basically, I'm asking how to mock a method which is dependent on a random number. How do I do this? I assume it's mocking, but my attempt doesn't work. Thanks