我有一个使用 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 到类的顶部修复了卡住问题。但是我遇到了这个方法没有被 mock 的问题。
最佳答案
尝试在测试的类级别而不是方法级别使用 @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();
}
}
关于java - 模拟 SecureRandom::nextInt(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375700/