我想按CPU時間排序所有Java線程。我使用ThreadMXBean通過線程ID獲取線程的CPU時間。比較器用於排序線程標識。Java,單元測試嘲笑mxbean
public class ThreadStats{
private static ThreadMXBean mxbean = ManagementFactory.getThreadMXBean();
class ThreadCPUCompare implements Comparator<Long>{
@Override
public int compare(Long threadId1, Long threadId2) {
return Long.compare(mxbean.getThreadCpuTime(threadId2), mxbean.getThreadCpuTime(threadId1));
}
}
}
而且我已經做了以下的單元測試:
@RunWith(MockitoJUnitRunner.class)
public class ThreadStatsTest {
@InjectMocks ThreadCPUCompare comperator = new ThreadStats().new ThreadCPUCompare();
@Mock ThreadMXBean mxbean;
@Test
public void threadCPUSortTest() {
Mockito.when(mxbean.getThreadCpuTime(1L)).thenReturn(3L);
Mockito.when(mxbean.getThreadCpuTime(2L)).thenReturn(2L);
Mockito.when(mxbean.getThreadCpuTime(3L)).thenReturn(4L);
Mockito.when(mxbean.getThreadCpuTime(4L)).thenReturn(1L);
List<Long>expectedList = new ArrayList<Long>();
expectedList.add(3L);
expectedList.add(1L);
expectedList.add(2L);
expectedList.add(4L);
List<Long>actualList = new ArrayList<Long>();
actualList.add(4L);
actualList.add(2L);
actualList.add(3L);
actualList.add(1L);
//Sorting of the actual list
Collections.sort(actualList, comperator);
assertEquals(expectedList, actualList);
}
}
,但我不能讓測試工作。我想因爲嘲笑不起作用。有人能告訴我如何解決單元測試嗎?
不知道,但你會不會需要調用'驗證(MXBean的)'? – uniknow