Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a final class with mockito

People also ask

Can we Mock final class with Mockito?

Configure Mockito for Final Methods and ClassesBefore we can use Mockito for mocking final classes and methods, we have to configure it. Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

Can you Mock a final method?

Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.

How do you use a Mock maker inline?

Option 2: Adding a file to enable the Mock maker inlineCreate a resources directory in your test directory if you do not have one. In resources create the directory mockito-extensions and in that directory the file org. mockito. plugins.

What can be mocked with Mockito?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.


Mockito 2 now supports final classes and methods!

But for now that's an "incubating" feature. It requires some steps to activate it which are described in What's New in Mockito 2:

Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to enable mockability of these types. As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line:

mock-maker-inline

After you created this file, Mockito will automatically use this new engine and one can do :

 final class FinalClass {
   final String finalMethod() { return "something"; }
 }

 FinalClass concrete = new FinalClass(); 

 FinalClass mock = mock(FinalClass.class);
 given(mock.finalMethod()).willReturn("not anymore");

 assertThat(mock.finalMethod()).isNotEqualTo(concrete.finalMethod());

In subsequent milestones, the team will bring a programmatic way of using this feature. We will identify and provide support for all unmockable scenarios. Stay tuned and please let us know what you think of this feature!


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

add this in your gradle file:

testImplementation 'org.mockito:mockito-inline:2.13.0'

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

...


add this in your build file:

  • if using gradle: build.gradle
testImplementation 'org.mockito:mockito-inline:2.13.0'
  • if using maven: pom.xml
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>2.13.0</version>
    <scope>test</scope>
</dependency>

this is a configuration to make mockito work with final classes

If you faced the Could not initialize inline Byte Buddy mock maker. (This mock maker is not supported on Android.) Add the Byte Buddy dependency to your build.gradle file:

testImplementation 'net.bytebuddy:byte-buddy-agent:1.10.19'

src: https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy


You cannot mock a final class with Mockito, as you can't do it by yourself.

What I do, is to create a non-final class to wrap the final class and use as delegate. An example of this is TwitterFactory class, and this is my mockable class:

public class TwitterFactory {

    private final twitter4j.TwitterFactory factory;

    public TwitterFactory() {
        factory = new twitter4j.TwitterFactory();
    }

    public Twitter getInstance(User user) {
        return factory.getInstance(accessToken(user));
    }

    private AccessToken accessToken(User user) {
        return new AccessToken(user.getAccessToken(), user.getAccessTokenSecret());
    }

    public Twitter getInstance() {
        return factory.getInstance();
    }
}

The disadvantage is that there is a lot of boilerplate code; the advantage is that you can add some methods that may relate to your application business (like the getInstance that is taking a user instead of an accessToken, in the above case).

In your case I would create a non-final RainOnTrees class that delegate to the final class. Or, if you can make it non-final, it would be better.


Use Powermock. This link shows, how to do it: https://github.com/jayway/powermock/wiki/MockFinal


In Mockito 3 and more I have the same problem and fixed it as from this link

Mock Final Classes and Methods with Mockito as follow

Before Mockito can be used for mocking final classes and methods, it needs to be > configured.

We need to add a text file to the project's src/test/resources/mockito-extensions directory named org.mockito.plugins.MockMaker and add a single line of text:

mock-maker-inline

Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.


Just to follow up. Please add this line to your gradle file:

testCompile group: 'org.mockito', name: 'mockito-inline', version: '2.8.9'

I have tried various version of mockito-core and mockito-all. Neither of them work.