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

How Can I Mock Final Classes and Methods with Mockito?

Patricia Arquette
Release: 2024-12-11 04:02:10
Original
150 people have browsed it

How Can I Mock Final Classes and Methods with Mockito?

Mocking Private or Final Methods/Classes with Mockito

When working with testing, mocking final classes or methods is a common challenge. Mockito, a popular mocking framework, traditionally faced limitations in this aspect. However, with the release of Mockito v2, this obstacle has been overcome.

To mock a final class with Mockito v2, follow these steps:

  1. Include Mockito v2 in Gradle:

    testImplementation 'org.mockito:mockito-inline:2.13.0'
    Copy after login
  2. Mock the Class Directly:

    // Given
    FinalClass finalClass = mock(FinalClass.class);
    Copy after login

    Note that you do not need to declare the @Mock annotation, as in older Mockito versions.

Limitations of Mockito v1:

As mentioned in the Mockito FAQ, Mockito v1 has limitations when it comes to mocking final classes. This is because final classes cannot be dynamically generated during runtime, a requirement for mocking.

What are the limitations of Mockito

...

Cannot mock final classes
Copy after login

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