How to mock Thread.class with Mockito?

Viewed 13273

As part of my unit tests, I am trying to mock the Thread.class isAlive() method to return true using Mockito. Below is my code:

final Thread mockThread = Mockito.mock(Thread.class);
Mockito.when(mockThread.isAlive()).thenReturn(true);

This is giving me the following exception on the second line:

Exception in thread "main" org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles); Also, this error might show up because: 1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. Mocking methods declared on non-public parent classes is not supported. 2. inside when() you don't call method on mock but on some other object.

I have used Mockito many times this way without issue. Is there some issue with mocking Thread.class? I have searched around with no luck.

4 Answers
Related