Home > Java > javaTutorial > How Can I Mock Final Classes with Mockito?

How Can I Mock Final Classes with Mockito?

Barbara Streisand
Release: 2024-12-31 17:09:15
Original
505 people have browsed it

How Can I Mock Final Classes with Mockito?

Mocking Final Classes in Mockito

When working with final classes, testing can become challenging due to their immutability. To overcome this hurdle, Mockito provides a solution in its version 2.

Implementation with Mockito v2

To mock final classes with Mockito v2, follow these steps:

  1. Add the following to your gradle file:
testImplementation 'org.mockito:mockito-inline:2.13.0'
Copy after login
  1. Import the org.mockito.MockedStatic class.
  2. Use MockedStatic to mock the final class:
@MockedStatic(RainOnTrees.class)
public class SeasonsTest {
    // Test methods here
}
Copy after login

Limitations with Mockito v1

Mocking final classes is not possible with Mockito v1. This is explicitly stated in the Mockito FAQ:

"Cannot mock final classes"

Alternatives for Mockito v1

If using Mockito v1, consider alternative solutions such as:

  • Using reflection to modify the final class.
  • Using a mocking framework that supports final class mocking, such as PowerMock.

The above is the detailed content of How Can I Mock Final Classes with 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