371

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?

LisaMM
  • 675
  • 1
  • 16
  • 28
buttowski
  • 4,657
  • 8
  • 27
  • 33
  • 13
    Mockito does not allow it, however PowerMock does. – fge Jan 12 '13 at 11:28
  • 3
    As of Mockito 2.x, Mockito now supports mocking of final classes and methods. – Kent Mar 22 '18 at 23:54
  • Possible duplicate of [Mock final class with Mockito 2](https://stackoverflow.com/questions/40979402/mock-final-class-with-mockito-2) – eliasah Jul 25 '18 at 09:41

28 Answers28

298

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

...

akshay bhange
  • 2,320
  • 2
  • 28
  • 46
  • 3
    This didn't work for me in Scala (with sbt modifications). – micseydel Oct 22 '19 at 17:11
  • 18
    This wasn't enough for me. I also had to create src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker with "mock-maker-inline" in it as per https://www.baeldung.com/mockito-final – micseydel Oct 22 '19 at 17:17
  • 1
    Mockito guide suggests to "replace", instead of "add", `mockito-inline` with `mockito-core`. https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#Mocking_Final – Hiro Apr 22 '21 at 17:19
  • 1
    With newer versions of mockito (3+?) there is no need for this additional dependency of `mockito-inline`. Just the "org.mockito.plugins.MockMaker" file from answer https://stackoverflow.com/a/40018295/1417088 is needed. – kajk Jul 22 '21 at 14:12
  • I only needed to replace `mockito-core:3.12.4` with `mockito-inline:3.12.4`. No fiddling with `MockMaker`. Maybe different versions have different idiosyncrasies. – Big McLargeHuge Feb 25 '23 at 01:07
287

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!

Community
  • 1
  • 1
WindRider
  • 11,958
  • 6
  • 50
  • 57
  • 39
    I still get an error: **Cannot mock/spy class android.content.ComponentName Mockito cannot mock/spy because : - final class** – IgorGanapolsky Mar 09 '17 at 16:06
  • 6
    Make sure you put the `org.mockito.plugins.MockMaker` file in the correct folder. – WindRider Mar 10 '17 at 09:41
  • 9
    I also am getting the error even after following the above mentioned: Mockito cannot mock/spy because : - final class – rcde0 Mar 24 '17 at 09:33
  • User `org.mockito:mockito-core` instead `org.mockito:mockito-android` to fix the error @rcde0 – Nam Vo Apr 18 '17 at 07:54
  • 10
    @vCillusion this answer isn't related to PowerMock in any way. – Line Oct 04 '17 at 11:28
  • 8
    I followed these instructions but I still couldn't make this work, did anyone have to do anything else? – Franco May 31 '18 at 06:42
  • 3
    Maker sure you have mockito version 2.X.X – Maciek Kreft Dec 06 '18 at 00:34
  • I am using it with Scala, it works fine when I run test cases for my individual module but when whole application tests run in the pipeline then it fails saying "Mockito can not spy/mock". Any Hint? – Yogesh Patil Mar 15 '19 at 16:15
  • NB this mocks final methods and classes but not *static* methods, as of yet. – rogerdpack Aug 23 '19 at 22:01
  • If you are on Windows OS, make sure you create the file without `.txt` extension. – Imran Sep 24 '19 at 15:09
  • 2
    Make sure that `mock-maker-inline` is a SINGLE LINE in `src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker`. – Yev Kanivets Nov 19 '19 at 10:56
  • Very interesting! It did really go around the Mockito final class restriction. – Jose Tepedino Nov 25 '19 at 02:03
  • This didn't work for me then a few minutes later "magically started working" maybe a `maven clean` helps? – rogerdpack Dec 24 '19 at 19:06
  • It did work for me, I did one more step forward, i.e. cleaned the project and run the test case after that. – Ram Aug 19 '20 at 12:25
  • Mine also didn't work until I found org.mockito.plugins.MockMaker I created from Eclipse(Mac) got an extra space at the end. Everything is woking after rename that file to the correct one. – barryku Aug 29 '20 at 02:18
  • Is there a way to achieve this programmatically now? – n1nsa1d00 Sep 30 '20 at 12:04
  • @MarcoDufal you can add `testImplementation 'org.mockito:mockito-inline:X.X.X'` instead of creating the file manually – Stachu Dec 04 '20 at 12:16
  • I added this file mistakenly in Res folder instead Resouces folder. Now it's working fine. – M.Muzammil Aug 18 '21 at 08:15
  • I just get `Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)` checked the folder structure, it is single line, no spelling problem, clean and rebuild. testImplementation "org.mockito:mockito-core:2.13.0" – BabyishTank Aug 29 '21 at 01:14
  • I found the solution for above problem. Need to use the kotlin version for Android: androidTestImplementation "org.mockito.kotlin:mockito-kotlin:$mockitoKotlinVersion" and make sure using import import org.mockito.kotlin.* – BabyishTank Sep 06 '21 at 20:20
  • I needed both: `testImplementation 'org.mockito:mockito-core:4.2.0'` and `testImplementation 'org.mockito:mockito-inline:4.2.0'` – ciaranodc Jan 14 '22 at 14:04
  • 1
    After 4 hours of searching, I found the solution in another application on Github. But in the end, this works like a charm. Add a single file with single line to test folder like image boom, solved. [link](https://ibb.co/LgVq5HD) – slhklc Apr 14 '22 at 12:02
91

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

bernard paulus
  • 1,644
  • 1
  • 21
  • 33
BennyP
  • 1,737
  • 1
  • 18
  • 24
43

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.

Luigi R. Viggiano
  • 8,659
  • 7
  • 53
  • 66
  • 7
    +1. If desired, you can use something like Lombok's `@Delegate` to handle a lot of the boilerplate. – ruakh Jun 29 '14 at 20:08
  • 2
    @luigi can you add code snippet for Junit as an Example. I tried to create Wrapper for my final class, but couldn't fiugre out, how to test it. – Incredible Jul 13 '16 at 13:45
34

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.

Community
  • 1
  • 1
Sattar
  • 2,453
  • 2
  • 33
  • 47
24

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

jobbert
  • 3,297
  • 27
  • 43
Gábor Lipták
  • 9,646
  • 2
  • 59
  • 113
  • 37
    I think PowerMock is like one of those pieces of medicine that should only go out on "prescription" base. In the sense of: one should make it very clear that PowerMock has **a lot** of problems; and that using it is like the ultimate last resort; and should be avoided as much as possible. – GhostCat Jun 16 '16 at 11:24
  • 1
    why do you say that? – PragmaticProgrammer Jul 05 '19 at 17:32
  • I was using `Powermock` for mocking final classes and static methods to increase my coverage that was officially checked on `Sonarqube`. Coverage was 0% since SonarQube , for what ever reason does not recognize classes that use Powermock anywhere inside it. I took me and my team quite some time to realize it from some thread online. So that is just one of the reasons to be careful with Powermock and probably don't use it. – amer Dec 17 '19 at 12:57
  • 2
    Now you can get done everything using the Mockito and no need to use the Power mock to the dependency. – Arefe Jan 31 '22 at 15:00
20

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.

Michael_Zhang
  • 333
  • 2
  • 7
  • 1
    To add to this, one thing i observed was that if you are using Powermock along with mockito; then adding the mockmaker plugin file in 'src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker' wouldn't be useful in mocking final classes. Instead, adding a dependency like mentioned by Michael_Zhang above would solve the issue of mocking final classes. Also, make sure you are using Mockito 2 instead of Mockito1 – dishooom Mar 23 '18 at 17:05
12

I had the same problem. Since the class I was trying to mock was a simple class, I simply created an instance of it and returned that.

user1945457
  • 304
  • 1
  • 3
  • 7
  • 4
    Absolutely, why mock a simple class? Mocking is for 'expensive' interactions: other services, engines, data classes etc. – StripLight Jan 17 '14 at 09:08
  • 7
    If you create an instance of that, you cannot apply the Mockito.verify methods on it afterwards. The main use of mocks is to be able to test some of its methods. – riroo May 12 '16 at 15:29
12

I guess you made it final because you want to prevent other classes from extending RainOnTrees. As Effective Java suggests (item 15), there's another way to keep a class close for extension without making it final:

  1. Remove the final keyword;

  2. Make its constructor private. No class will be able to extend it because it won't be able to call the super constructor;

  3. Create a static factory method to instantiate your class.

    // No more final keyword here.
    public class RainOnTrees {
    
        public static RainOnTrees newInstance() {
            return new RainOnTrees();
        }
    
    
        private RainOnTrees() {
            // Private constructor.
        }
    
        public void startRain() {
    
            // some code here
        }
    }
    

By using this strategy, you'll be able to use Mockito and keep your class closed for extension with little boilerplate code.

Flávio Faria
  • 6,575
  • 3
  • 39
  • 59
7

Actually there is one way, which I use for spying. It would work for you only if two preconditions are satisfied:

  1. You use some kind of DI to inject an instance of final class
  2. Final class implements an interface

Please recall Item 16 from Effective Java. You may create a wrapper (not final) and forward all call to the instance of final class:

public final class RainOnTrees implement IRainOnTrees {
    @Override public void startRain() { // some code here }
}

public class RainOnTreesWrapper implement IRainOnTrees {
    private IRainOnTrees delegate;
    public RainOnTreesWrapper(IRainOnTrees delegate) {this.delegate = delegate;}
    @Override public void startRain() { delegate.startRain(); }
}

Now not only can you mock your final class but also spy on it:

public class Seasons{
    RainOnTrees rain;
    public Seasons(IRainOnTrees rain) { this.rain = rain; };
    public void findSeasonAndRain(){
        rain.startRain();
   }
}

IRainOnTrees rain = spy(new RainOnTreesWrapper(new RainOnTrees()) // or mock(IRainOnTrees.class)
doNothing().when(rain).startRain();
new Seasons(rain).findSeasonAndRain();
Cœur
  • 37,241
  • 25
  • 195
  • 267
xuesheng
  • 3,396
  • 2
  • 29
  • 38
6

Another workaround, which may apply in some cases, is to create an interface that is implemented by that final class, change the code to use the interface instead of the concrete class and then mock the interface. This lets you separate the contract (interface) from the implementation (final class). Of course, if what you want is really to bind to the final class, this will not apply.

andresp
  • 1,624
  • 19
  • 31
6

Time saver for people who are facing the same issue (Mockito + Final Class) on Android + Kotlin. As in Kotlin classes are final by default. I found a solution in one of Google Android samples with Architecture component. Solution picked from here : https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample

Create following annotations :

/**
 * This annotation allows us to open some classes for mocking purposes while they are final in
 * release builds.
 */
@Target(AnnotationTarget.ANNOTATION_CLASS)
annotation class OpenClass

/**
 * Annotate a class with [OpenForTesting] if you want it to be extendable in debug builds.
 */
@OpenClass
@Target(AnnotationTarget.CLASS)
annotation class OpenForTesting

Modify your gradle file. Take example from here : https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/build.gradle

apply plugin: 'kotlin-allopen'

allOpen {
    // allows mocking for classes w/o directly opening them for release builds
    annotation 'com.android.example.github.testing.OpenClass'
}

Now you can annotate any class to make it open for testing :

@OpenForTesting
class RepoRepository 
Ozeetee
  • 126
  • 1
  • 5
  • This works well at app level build.gradle but what can we do to get this on library level? – Sumit T Jan 08 '19 at 20:03
  • Can you elaborate a bit? Usually, use facade pattern to connect to libs. And mock these facade classes to test the app. In this way we don't need to mock any lib classes. – Ozeetee Jan 11 '19 at 21:07
  • 1
    I don't see any test-specific options. The procedure is fully matches with the [official instruction](https://kotlinlang.org/docs/reference/compiler-plugins.html#using-in-gradle). So class will be open in production as well. – Ilya Serbis Feb 01 '21 at 20:45
5

Give this a try:

Mockito.mock(SomeMockableType.class,AdditionalAnswers.delegatesTo(someInstanceThatIsNotMockableOrSpyable));

It worked for me. "SomeMockableType.class" is the parent class of what you want to mock or spy, and someInstanceThatIsNotMockableOrSpyable is the actual class that you want to mock or spy.

For more details have a look here

sakis kaliakoudas
  • 2,039
  • 4
  • 31
  • 51
  • 3
    It should be noticed that delegates is very different from native spy mocking. In a native mockito spy, "this" in the instance reference to the spy itself (because is use subclass) However, in delegate, "this" will be the real object someInstanceThatIsNotMockableOrSpyable. Not the spy. Thus, there is no way to doReturn/verify for self-calling functions. – Dennis C Jan 29 '15 at 10:04
  • 1
    can you put up a example? – Vishwa Ratna Sep 12 '19 at 12:44
4

This can be done if you are using Mockito2, with the new incubating feature which supports mocking of final classes & methods.

Key points to note:
1. Create a simple file with the name “org.mockito.plugins.MockMaker” and place it in a folder named “mockito-extensions”. This folder should be made available on the classpath.
2. The content of the file created above should be a single line as given below:
mock-maker-inline

The above two steps are required in order to activate the mockito extension mechanism and use this opt-in feature.

Sample classes are as follows:-

FinalClass.java

public final class FinalClass {

public final String hello(){
    System.out.println("Final class says Hello!!!");
    return "0";
}

}

Foo.java

public class Foo {

public String executeFinal(FinalClass finalClass){
    return finalClass.hello();
}

}

FooTest.java

public class FooTest {

@Test
public void testFinalClass(){
    // Instantiate the class under test.
    Foo foo = new Foo();

    // Instantiate the external dependency
    FinalClass realFinalClass = new FinalClass();

    // Create mock object for the final class. 
    FinalClass mockedFinalClass = mock(FinalClass.class);

    // Provide stub for mocked object.
    when(mockedFinalClass.hello()).thenReturn("1");

    // assert
    assertEquals("0", foo.executeFinal(realFinalClass));
    assertEquals("1", foo.executeFinal(mockedFinalClass));

}

}

Hope it helps.

Complete article present here mocking-the-unmockable.

ksl
  • 41
  • 1
  • 4
  • You should include the answer here and not link to an external site. If the procedure is long you could include an overview. – rghome Feb 05 '17 at 11:01
  • please ensure below annotations are used when mocking @RunWith(PowerMockRunner.class) @PrepareForTest({AFinalClass.class}) – vCillusion Aug 08 '17 at 11:59
  • 1
    @vCillusion - The example I have shown just uses the Mockito2 API.Using the opt-in feature of Mockito2, one can mock the final classes directly without the need to use Powermock. – ksl Aug 08 '17 at 21:45
3

Yes same problem here, we cannot mock a final class with Mockito. To be accurate, Mockito cannot mock/spy following:

  • final classes
  • anonymous classes
  • primitive types

But using a wrapper class seems to me a big price to pay, so get PowerMockito instead.

BJYC
  • 354
  • 2
  • 10
2

I think you need think more in principle. Instead you final class use his interface and mock interface instead.

For this:

 public class RainOnTrees{

   fun startRain():Observable<Boolean>{

        // some code here
   }
}

add

interface iRainOnTrees{
  public void startRain():Observable<Boolean>
}

and mock you interface:

 @Before
    fun setUp() {
        rainService= Mockito.mock(iRainOnTrees::class.java)

        `when`(rainService.startRain()).thenReturn(
            just(true).delay(3, TimeUnit.SECONDS)
        )

    }
Serg Burlaka
  • 2,351
  • 24
  • 35
2

If you need to use Mockito in an instrumented test in Android (i. e. running in an Android device), you cannot use mockito-inline. There is a special mockito-android version which doesn't solve the "final class" problem either. The only solution which seems to work is the Dexmaker library. The only limitation is that it works only in Android P (Android 9, API 28) and higher. It can be imported as follows:

androidTestImplementation "com.linkedin.dexmaker:dexmaker-mockito-inline:2.28.1"

Beware that there is also a "dexmaker-mockito" version which doesn't work for final classes either. Make sure you import "dexmaker-mockito-inline".

Edit: Eventually I just migrated everything to Mockk to get rid of all the problems.

Miloš Černilovský
  • 3,846
  • 1
  • 28
  • 30
1

Please look at JMockit. It has extensive documentation with a lot of examples. Here you have an example solution of your problem (to simplify I've added constructor to Seasons to inject mocked RainOnTrees instance):

package jmockitexample;

import mockit.Mocked;
import mockit.Verifications;
import mockit.integration.junit4.JMockit;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMockit.class)
public class SeasonsTest {

    @Test
    public void shouldStartRain(@Mocked final RainOnTrees rain) {
        Seasons seasons = new Seasons(rain);

        seasons.findSeasonAndRain();

        new Verifications() {{
            rain.startRain();
        }};
    }

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

    }

    public class Seasons {

        private final RainOnTrees rain;

        public Seasons(RainOnTrees rain) {
            this.rain = rain;
        }

        public void findSeasonAndRain() {
            rain.startRain();
        }

    }
}
Marcin
  • 1,469
  • 14
  • 23
1

Solutions provided by RC and Luigi R. Viggiano together is possibly the best idea.

Although Mockito cannot, by design, mock final classes, the delegation approach is possible. This has its advantages:

  1. You are not forced to change your class to non-final if that is what your API intends in the first place (final classes have their benefits).
  2. You are testing the possibility of a decoration around your API.

In your test case, you deliberately forward the calls to the system under test. Hence, by design, your decoration does not do anything.

Hence you test can also demonstrate that the user can only decorate the API instead of extending it.

On a more subjective note: I prefer keeping the frameworks to a minimum, which is why JUnit and Mockito are usually sufficient for me. In fact, restricting this way sometimes forces me to refactor for good as well.

Neel
  • 2,100
  • 5
  • 24
  • 47
1

If you trying to run unit-test under the test folder, the top solution is fine. Just follow it adding an extension.

But if you want to run it with android related class like context or activity which is under androidtest folder, the answer is for you.

Allen
  • 2,979
  • 1
  • 29
  • 34
1

Add these dependencies for run mockito successfully :

testImplementation 'org.mockito:mockito-core:2.24.5'
testImplementation "org.mockito:mockito-inline:2.24.5"

HandyPawan
  • 1,018
  • 1
  • 11
  • 16
1

Mocking final classes is not supported for mockito-android as per this GitHub issue. You should use Mockk instead for this.

For both unit test and ui test, you can use Mockk with no problem.

metis
  • 1,024
  • 2
  • 10
  • 26
0

As others have stated, this won't work out of the box with Mockito. I would suggest using reflection to set the specific fields on the object that is being used by the code under test. If you find yourself doing this a lot, you can wrap this functionality in a library.

As an aside, if you are the one marking classes final, stop doing that. I ran across this question because I am working with an API where everything was marked final to prevent my legitimate need for extension (mocking), and I wish that the developer had not assumed that I would never need to extend the class.

Tom N.
  • 96
  • 4
  • 1
    Public API classes should be open for extension. Wholly agree. However, in a private code-base, `final` should be the default. – ErikE Sep 04 '18 at 04:44
0

For us, it was because we excluded mockito-inline from koin-test. One gradle module actually needed this and for reason only failed on release builds (debug builds in the IDE worked) :-P

kenyee
  • 2,309
  • 1
  • 24
  • 32
0

For final class add below to mock and call static or non static.

1- add this in class level @SuppressStatucInitializationFor(value ={class name with package})
2- PowerMockito.mockStatic(classname.class) will mock class
3- then use your when statement to return mock object when calling method of this class.

Enjoy

0

I was able to overcome this message:

org.mockito.exceptions.base.MockitoException: Cannot mock/spy class org.slf4j.impl.Log4jLoggerAdapter Mockito cannot mock/spy because :

  • final or anonymous class

from this: log = spy(log);

By using this instead:

log = mock(Logger.class);

Then it works.

I guess that "default" logger adapter is an instance of a final class so I couldn't "spy" it, but I could mock the whole thing. Go figure...

This may mean that you could substitute it for some other "non final" instance if you have that handy, as well. Or a simplified version, etc. FWIW...

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
0

I am writing the steps I followed after various unsuccessful attempts to mock final/private classes and their methods in Java 11, which finally worked for me.

  1. Create a file named org.mockito.plugins.MockMaker inside your test/resources/mockito-extensions folder. Please create mockito-extensions folder if not present already.
  2. Add a single line mock-maker-inline as the content of the above org.mockito.plugins.MockMaker file
  3. Add
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "jdk.internal.reflect.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
@PrepareForTest(Utility.class)

annotations at the class level.

Setup process in the test class

  @Before
  public void setup () {
    MockitoAnnotations.initMocks(this);
    Mockito.mockStatic(ClassToBeMocked.class); 
  }
  1. Use Mockito.when(..).thenReturn(..) for assertions
  2. In case of multiple test cases, add the below code
  @After
  public void after() {
        Mockito.framework().clearInlineMocks();
  }

The mockito version which I am using: 3.9.0 Java version: 11

-5

Didn't try final, but for private, using reflection remove the modifier worked ! have checked further, it doesn't work for final.

Jackie
  • 25,199
  • 6
  • 33
  • 24