java-addict301 java-addict301 - 1 year ago 104
Java Question

How to mock Thread.class with Mockito?

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.

Answer Source

Thread.isAlive() is declared with the final modifier. It cannot be mocked by Mockito.
Use Powermock or Mockito 2 that adds this feature :

For a long time our users suffered a disbelief when Mockito refused to mock a final class. ... Mocking of final classes and methods is an incubating, opt-in feature

Or another way : change the way to unit test your class.

Do you really need to rely on isAlive() to unit test ?

If you really need it, you could also use a wrapper class that composes a Thread instance and that delegates the processing to the composed Thread.
This could implement Runnable for example.
In this way you could naturally mock the isAlive() method of this wrapper class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download