Tôi đang cố gắng xác minh rằng phương thức Collections.shuffle() đã được gọi trong một trong các lớp của tôi. Tôi đọc qua tài liệu (ít) về PowerMock với Mockito và đọc qua các câu hỏi SO khác giải quyết vấn đề này và không nhận được giải pháp.Giả lập tĩnh với PowerMock và Mockito không hoạt động
@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
}
}
Với mã trên, tôi mong đợi đơn vị kiểm tra vượt qua. Tuy nhiên, kiểm tra đơn vị không thành công như sau:
Wanted but not invoked java.util.Collections.shuffle([]);
Actually, there were zero interactions with this mock.
Tôi đang làm gì sai?
Cảm ơn
EDIT: Theo gợi ý dưới đây tôi đã cố gắng điều sau đây, và tôi nhận được lỗi tương tự.
@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));
}
}
Điều gì sẽ xảy ra nếu bạn nới lỏng hạn chế trên đối sánh từ 'anyListOf' thành' any (List.class) '? Điều gì sẽ xảy ra nếu bạn thêm 'ClassToTest' vào chú thích' @ PrepareForTest'? –