buttowski buttowski - 1 month ago 15
Java Question

How to mock a final class with mockito

I have a final class, something like this:

public final class RainOnTrees{

public void startRain(){

// some code here
}
}


I am using this class in some other class like this:

public class Seasons{

RainOnTrees rain = new RainOnTrees();

public void findSeasonAndRain(){

rain.startRain();

}
}


and in my JUnit test class for
Seasons.java
I want to mock the
RainOnTrees
class. How can I do this with Mockito?

RC. RC.
Answer

Mocking final/static classes/methods is possible with Mockito v2 only.

This is not possible with Mockito v1, from the Mockito FAQ:

What are the limitations of Mockito

  • Needs java 1.5+

  • Cannot mock final classes

...

Comments