Java Mocking SecureRandom::nextInt()

Java Mocking SecureRandom::nextInt(),java,unit-testing,junit,mockito,powermock,Java,Unit Testing,Junit,Mockito,Powermock,我有一个类,它使用SecureRandom实例并获取下一个随机数 比如说: public class ExampleClass() { public void method() { Random sr = new SecureRandom(); System.out.printf("%d %n", sr.nextInt(1)); System.out.printf("%d %n", sr.nextInt(1)); } } 测试代码 @RunW

我有一个类,它使用SecureRandom实例并获取下一个随机数

比如说:

public class ExampleClass() {
   public void method() { 
      Random sr = new SecureRandom();
      System.out.printf("%d %n", sr.nextInt(1));
      System.out.printf("%d %n", sr.nextInt(1));
   }
}

测试代码

@RunWith(PowerMockRunner.class)
public class ExampleClassTest {
...
@Test
@PrepareOnlyThisForTest(SecureRandom.class)
public void mockedTest() throws Exception {

    Random spy = PowerMockito.spy(new SecureRandom());

    when(spy, method(SecureRandom.class, "nextInt", int.class))
            .withArguments(anyInt())
            .thenReturn(3, 0);


    instance.method();
}
当我试图运行单元测试时,单元测试最终被冻结。当我尝试只调试该方法时,JUnit会报告该测试不是该类的成员

No tests found matching Method mockedTest(ExampleClass) from org.junit.internal.requests.ClassRequest@6a6cb05c 

编辑:将@PrepareOnlyThisForTest移动到perparefortest到类的顶部修复了冻结问题。然而,我得到的问题是,该方法没有被嘲笑

尝试在测试的类级别而不是方法级别使用@PrepareForTest

@RunWith(PowerMockRunner.class)
@PrepareForTest(SecureRandom.class) 
public class ExampleClassTest {
...
}
编辑:为了调用模拟,您需要执行以下操作:

1) 将ExampleClass添加到PrepareForTest注释:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SecureRandom.class, ExampleClass.class}) 
public class ExampleClassTest {
...
}
2) 模拟SecureRandom的构造函数调用:

SecureRandom mockRandom = Mockito.mock(SecureRandom.class);
PowerMockito.whenNew(SecureRandom.class).withNoArguments().thenReturn(mockRandom);
下面给出了一个工作示例:

@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();
   }
}

这很管用,但现在我遇到了一个问题,SecureRandom调用本机实现而不是模拟。这很管用!谢谢在Python上的mocker和java中的Mockito/Powermock之间,我有很多东西需要习惯。