模拟SecureRandom :: nextInt()

时间:2014-04-29 21:32:42

标签: 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));
   }
}

测试代码

@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移动到PerpareForTests到类的顶部修复了冻结问题。但是我遇到的问题是该方法没有被嘲笑。

1 个答案:

答案 0 :(得分:2)

尝试在测试的类级别使用@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();
   }
}