我想驗證Collections.shuffle()方法是在我的一個類中調用的。我用Mockito閱讀了關於PowerMock的(少量)文檔,並閱讀了解決這個問題的其他SO問題,但沒有得到解決方案。StaticMocking與PowerMock和Mockito不起作用
@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));
}
}
如果你將匹配器的限制從'anyListOf'放到'any(List.class)'中,會發生什麼?如果將'ClassToTest'添加到'@ PrepareForTest'註釋中會發生什麼? –