【发布时间】:2014-04-29 21:32:41
【问题描述】:
我有一个使用 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 到类的顶部修复了冻结问题。但是我遇到的问题是该方法没有被嘲笑。
【问题讨论】:
标签: java unit-testing junit mockito powermock