Home > Java > javaTutorial > How Can I Mock a Final Class in Mockito?

How Can I Mock a Final Class in Mockito?

Barbara Streisand
Release: 2024-12-28 21:04:15
Original
1052 people have browsed it

How Can I Mock a Final Class in Mockito?

Mocking Final Classes with Mockito

Problem:

You have a final class that you want to mock in a JUnit test. However, Mockito appears to have limitations in mocking final classes.

Detailed Question:

Consider the following example code:

Java

public final class RainOnTrees {
   public void startRain() {
      // some code here
   }
}
Copy after login

In another class:

Java

public class Seasons {
   RainOnTrees rain = new RainOnTrees();
   public void findSeasonAndRain() {
      rain.startRain();
   }
}
Copy after login

In the JUnit test class for Seasons.java, you want to mock the RainOnTrees class. How can you achieve this using Mockito?

Answer:

Beginning with Mockito v2, it has become possible to mock final classes. To enable this functionality, add the following to your Gradle file:

Java

testImplementation 'org.mockito:mockito-inline:2.13.0'
Copy after login

Note that mocking final classes was not feasible with Mockito v1. As mentioned in the Mockito FAQ:

"Cannot mock final classes"

For more information on the limitations of Mockito, refer to the official documentation.

The above is the detailed content of How Can I Mock a Final Class in Mockito?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template