Try using @PrepareForTest at the class level of your test, not at method level.
@RunWith(PowerMockRunner.class)
@PrepareForTest(SecureRandom.class)
public class ExampleClassTest {
...
}
Edit: In order to invoke the mock, you need to do the following:
1) Add the ExampleClass to the PrepareForTest annotation:
@RunWith(PowerMockRunner.class)
@PrepareForTest({SecureRandom.class, ExampleClass.class})
public class ExampleClassTest {
...
}
2) Mock the constructor call for SecureRandom:
SecureRandom mockRandom = Mockito.mock(SecureRandom.class);
PowerMockito.whenNew(SecureRandom.class).withNoArguments().thenReturn(mockRandom);
A working example is given below:
@RunWith(PowerMockRunner.class)
@PrepareForTest({SecureRandom.class, ExampleClass.class})
public class ExampleClassTest {
private ExampleClass example = new ExampleClass();
@Test
public void aTest() throws Exception {
SecureRandom mockRandom = Mockito.mock(SecureRandom.class);
PowerMockito.whenNew(SecureRandom.class).withNoArguments().thenReturn(mockRandom);
Mockito.when(mockRandom.nextInt(Mockito.anyInt())).thenReturn(3, 0);
example.method();
}
}