0

I want to unit test this method. I know i need to mock the mxbean, but i have no idea how to do that. Could someone show me how to unit test this method please?

@Override
public int compare(Long threadId1, Long threadId2) {
    ThreadMXBean mxbean = ManagementFactory.getThreadMXBean();
    return Long.compare(mxbean.getThreadCpuTime(threadId2), mxbean.getThreadCpuTime(threadId1));
}
1
  • I disagree, this isn't really the point. If you substitute the ManagementFactory call with any static call from the OPs own application, then it becomes a valid question. Commented Jun 3, 2016 at 15:00

1 Answer 1

1

As it is, it can't effectively be mocked. You need to move the local variable to a field.

ThreadMXBean mxbean = ManagementFactory.getThreadMXBean();

@Override
public int compare(Long threadId1, Long threadId2) {
    return Long.compare(mxbean.getThreadCpuTime(threadId2), mxbean.getThreadCpuTime(threadId1));
}

Now you can reassign the field to a mock in your test (I'll be using Mockito, but other frameworks exist as well):

@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));
}

But it's even nicer to use the Mockito JUnit Runner and have Mockito create mocks automatically:

@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));
    }


}

Finally: test get more readable if you replace all Mockito.* calls with static imports, e.g.

MyFoo foo = mock(MyFoo.class);
when(foo.bar()).thenReturn(baz);
Sign up to request clarification or add additional context in comments.

3 Comments

@NicolasFilotto apparently we have different experience with "real world" code. In my real world, we try to make code testable.
I love how people complain about other people's answers but don't provide their own. If you don't like the question, downvote or close it. If you don't like the answer, downvote it. But I'll be the judge of which questions I deem worthy of answering
Then feel free to ignore it. Or close it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.