我正在尝试验证 Collections.shuffle() 方法是否在我的一个类中被调用。我用 Mockito 通读了关于 PowerMock 的(小)文档,并通读了处理这个问题但没有得到解决的其他 SO 问题。
@RunWith(PowerMockRunner.class)
@PrepareForTest(Collections.class)
public class MyTest {
@Test
public void testShuffle() {
PowerMockito.mockStatic(Collections.class);
PowerMockito.doCallRealMethod().when(Collections.class);
Collections.shuffle(Mockito.anyListOf(Something.class));
ClassToTest test = new ClassToTest();
test.doSomething();
PowerMockito.verifyStatic(); // Verify shuffle was called exactly once
Collections.shuffle(Mockito.anyListOf(Something.class));
}
}
public class ClassToTest {
private final List<Something> list;
// ...
public void doSomething() {
Collections.shuffle(list);
// do more stuff
}
}
鉴于上面的代码,我希望单元测试通过。但是,单元测试失败如下:
Wanted but not invoked java.util.Collections.shuffle([]);
Actually, there were zero interactions with this mock.
我究竟做错了什么?
谢谢
编辑: 根据下面的建议,我尝试了以下方法,但我得到了同样的错误。
@RunWith(PowerMockRunner.class)
@PrepareForTest(Collections.class)
public class MyTest {
@Test
public void testShuffle() {
PowerMockito.mockStatic(Collections.class);
ClassToTest test = new ClassToTest();
test.doSomething();
PowerMockito.verifyStatic(); // Verify shuffle was called exactly once
Collections.shuffle(Mockito.anyListOf(Something.class));
}
}