我想对此方法进行单元测试。我知道我需要嘲笑 mxbean,但我不知道该怎么做。有人可以告诉我如何对此方法进行单元测试吗?
@Override
public int compare(Long threadId1, Long threadId2) {
ThreadMXBean mxbean = ManagementFactory.getThreadMXBean();
return Long.compare(mxbean.getThreadCpuTime(threadId2), mxbean.getThreadCpuTime(threadId1));
}
事实上,它不能有效地被嘲笑。您需要将局部变量移动到字段。
ThreadMXBean mxbean = ManagementFactory.getThreadMXBean();
@Override
public int compare(Long threadId1, Long threadId2) {
return Long.compare(mxbean.getThreadCpuTime(threadId2), mxbean.getThreadCpuTime(threadId1));
}
现在,您可以在测试中将该字段重新分配给模拟(我将使用 Mockito,但也存在其他框架):
@Test
public void yourTestMethod(){
YourClass yourClass = new YourClass();
ThreadMXBean mock = Mockito.mock(ThreadMXBean.class)
Mockito.when(mxbean.getThreadCpuTime(1L)).thenReturn(1);
Mockito.when(mxbean.getThreadCpuTime(2L)).thenReturn(2);
yourClass.mxbean = mock;
assertThat(yourClass.compare(1L, 2L), is(-1));
}
但是使用Mockito JUnit Runner并让Mockito自动创建模拟会更好:
@RunWith(MockitoJUnitRunner.class)
public class YourTest{
@InjectMocks YourClass yourClass = new YourClass();
@Mock ThreadMXBean mock;
@Test
public void yourTestMethodDoesntNeedToCreateMocksAnymore(){
Mockito.when(mxbean.getThreadCpuTime(1L)).thenReturn(1);
Mockito.when(mxbean.getThreadCpuTime(2L)).thenReturn(2);
assertThat(yourClass.compare(1L, 2L), is(-1));
}
}
最后:如果将所有 Mockito.* 调用替换为静态导入,测试将变得更可读,例如
MyFoo foo = mock(MyFoo.class);
when(foo.bar()).thenReturn(baz);