Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Thread.class with Mockito?

Tags:

java

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.

like image 274
java-addict301 Avatar asked Jan 30 '23 18:01

java-addict301


1 Answers

Thread.isAlive() is declared with the final modifier. It cannot be mocked by Mockito 1.
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.

like image 186
davidxxx Avatar answered Feb 02 '23 09:02

davidxxx