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);
Exception in thread "main" org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
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.
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
This could implement
Runnable for example.
In this way you could naturally mock the
isAlive() method of this wrapper class.