168

I'm getting following exception once tests is started:

    Testcase: treeCtorArgumentTest(com.xythos.client.drive.cachedtree.CachedTreeTest):  Caused an ERROR
Could not initialize plugin: interface org.mockito.plugins.MockMaker
java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker
    at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:66)
    at com.sun.proxy.$Proxy7.isTypeMockable(Unknown Source)
    at org.mockito.internal.util.MockUtil.typeMockabilityOf(MockUtil.java:29)
    at org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
    at org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:168)
    at org.mockito.internal.creation.MockSettingsImpl.confirm(MockSettingsImpl.java:162)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:64)
    at org.mockito.Mockito.mock(Mockito.java:1687)
    at org.mockito.Mockito.mock(Mockito.java:1600)
    at com.xythos.client.drive.cachedtree.CachedTreeTest.setUp(CachedTreeTest.java:51)
Caused by: java.lang.NoClassDefFoundError: net/bytebuddy/dynamic/loading/ClassLoadingStrategy
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.<init>(SubclassByteBuddyMockMaker.java:33)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.<init>(ByteBuddyMockMaker.java:22)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:54)
    at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:18)
    at org.mockito.internal.configuration.plugins.Plugins.<clinit>(Plugins.java:17)
    at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:24)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.dynamic.loading.ClassLoadingStrategy
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

This is my test:

package com.xythos.client.drive.cachedtree;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)

    public class CachedTreeTest {

        public CachedTreeTest() {
        }

        @Test
        public void treeCtorArgumentTest() {
        somemock m = mock(SomeClass.class);
        }
    }

I'm using NetBeans 8.2. I've downloaded mockito-core-2.7.0.jar, and then I select "Test Libraries"->"Add Jar" and added mockito-core-2.7.0.jar.

Classpath and everything looks ok, I',m still getting exception.

Any advice?

Paskas
  • 2,622
  • 2
  • 14
  • 10
  • 2
    Check solution at https://stackoverflow.com/a/41964561/4903889 – AskQ Dec 23 '17 at 18:12
  • Upgrading to a newer version of Mockito helped me solve this problem. – Yogesh Patil Mar 18 '19 at 15:02
  • Clearing Gradle cache and downloading all dependencies from scratch fixed it for me. (See: https://stackoverflow.com/a/13567793/4568679 for clearing cache) – Slav Oct 15 '19 at 11:26
  • I had a typo in the file `src/test/resources/org/powermock/extensions/configuration.properties` causing the exception shown. – jbaranski Jun 04 '21 at 19:03
  • I invalidated cache of IDE and restarted, it solved the problem for me – setiabb May 20 '22 at 09:54
  • My problem was that I had some private static final variables at the test class, when I removed these variables it worked again. – digoferra Feb 16 '23 at 09:55
  • Had this problem, mvn test worked fine on the commandline but Eclipse kept throwing this. Double checked m2 repo, tried to delete the mockito-inline folder/jar yet it was locked by Eclipse. That was a clue, to fix it all I did was close and reopen Eclipse - it's a different engine so ... – Adam D. Mar 21 '23 at 23:28

38 Answers38

115

If you are using powermock ensure that your dependencies point to:

org.powermock:powermock-api-mockito2

instead of

org.powermock:powermock-api-mockito
Addev
  • 31,819
  • 51
  • 183
  • 302
63

Missing reference to:

  • byte-buddy-1.6.5.jar
  • byte-buddy-agent-1.6.5.jar
  • objenesis-2.5.jar

Since Mockito 2.0.2 beta, Mockito-core has dependencies.

Paskas
  • 2,622
  • 2
  • 14
  • 10
  • 22
    those libraries are included by default, this is not the solution – Eduardo Oct 13 '17 at 14:11
  • I can confirm that adding the latest byte-budy (and more likely, the byte-buddy-agent) JARs to a "latest greatest" mockito setup help here. For me, the exception from the question showed up after enabling "mocking of final" classes with mockito 2. – GhostCat Apr 23 '18 at 08:49
  • 3
    these are transitive dependencies you do not have to add them explicitly. – Łukasz Rzeszotarski Feb 06 '19 at 12:45
  • For **`mockito 2.25.1`** you only need `objenesis-3.0.1.jar` and `byte-buddy-1.9.12.jar`. – user1485864 Mar 27 '19 at 13:28
  • 2
    thease deps are listed in the [maven page](https://mvnrepository.com/artifact/org.mockito/mockito-core/2.26.0) too, at the bottom of the page. Including it resolve the problem. – Davide Dec 20 '19 at 11:12
  • 3
    These are only included by default (as suggested by @Eduardo) if you are not using a build system (maven/gradle) to automatically resolve the dependencies, otherwise this could be the solution. – wlnirvana Dec 02 '20 at 06:45
  • The project currently I'm working on manually imports `jar` files, and this answer worked for me. – wonsuc Feb 24 '22 at 06:00
  • Thanks, had to explicitly add these 3 for it to work – ServletException Nov 13 '22 at 13:40
21

I had Byte Buddy on classpath (is transitive dep of Mockito 2.8.9) and still got the exception. Reason for me was that I ran the Unit tests with JRE instead of JDK. Switching to JDK worked for me.

Stefano L
  • 1,486
  • 2
  • 15
  • 36
  • 2
    How did you change this? – Taranmeet Singh Mar 08 '19 at 05:40
  • 3
    @TaranmeetSingh if you're running with Android Studio, go to File > Project Structure > SDK location, and check the paths to your JDK are correct. (You'll need to download a JDK if you haven't already from the Oracle website.) – Lydia Ralph May 15 '19 at 07:54
  • Hi @LydiaRalph thanks for the suggestion actually I had a altogether different problem. I was writing Unit test cases for one of the modules(which are also standalone android studio projects) but I had instead opened the whole project in android studio. Switching to the stand alone project solved this for me. – Taranmeet Singh May 16 '19 at 08:21
  • @Stefano , how to switch as I've not mentioned any where using jdk or jre – Tarun Aug 14 '19 at 06:15
  • This fixed it for me. I just removed the JRE from Eclipse's Java Runtimes, leaving only the JDK. – Guillaume F. Dec 18 '19 at 21:29
  • I keep forgetting doing this, Thanks a bunch. I should remove my JREs too – MathGuy Dec 08 '20 at 02:24
16

Well, after a lot of research , solution for me is super simple :

update Mockito lib version to latest

dependencies {
    testImplementation 'org.mockito:mockito-core:3.10.0'
    androidTestImplementation 'org.mockito:mockito-android:3.10.0'
}
fvolodimir
  • 445
  • 5
  • 3
  • 1
    This worked for me, problems immediately resolved after upgrading from 2.7.2 to 4.2.0. Note that you still need to set up the `mock-maker-inline` extension. – BenLewis Jan 03 '22 at 02:31
15

This problem with Mockito2 occurs if you enable the option to mock final classes.

This means when in your test/resources/mockito-extensions directory you have the file called org.mockito.plugins.MockMaker with the following content mock-maker-inline.

In that case byte-buddy, which is a transitive dependency for mockito-core, has the problem to attach own agent to the java process. But the problem occurs only when you use JRE.

The solution would be either:

  • Use JDK instead of JRE

or

  • add -javaagent:byte-buddy-agent-*.jar as a VM option
Łukasz Rzeszotarski
  • 5,791
  • 6
  • 37
  • 68
9

I had the same problem - same stacktrace appear in my log. It is typically problem with project setup... OR
The problem can be in the bytebuddys JARs if these were not downloaded correctly.
When I try to check class ClassLoadingStrategy manually then I get zip error.

In that case it is just enough manually delete the Byte Buddy from local maven directory, usually located at:
{home}/.m2/repository/net/bytebuddy/

The next try to run project or test they will be downloaded again and should work as expected.

Unfortunatelly common Java ClassLoader faces in the same way when class or jar missing as well as the jar is corrupted.

vdou
  • 281
  • 3
  • 5
  • There is another possibility: Hibernate also have `net.bytebuddy*` as a dependency, so may the dependencies being in conflict with each other. – ruzenhack Jun 15 '18 at 21:48
5

Problem: PowerMock + Mockito + TestNG + PowerMockTestCase

Sharing my problem/solution in case it helps anybody.

My dependencies were all pointed correctly:

testImplementation 'org.mockito:mockito-core:2.8.47'
testImplementation 'org.powermock:powermock-core:1.7.4'
testImplementation 'org.powermock:powermock-module-testng:1.7.4'
testImplementation 'org.powermock:powermock-api-mockito2:1.7.4'

But I still got the following error:

java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker

    at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:66)
    at com.sun.proxy.$Proxy11.isTypeMockable(Unknown Source)
    at org.mockito.internal.util.MockUtil.typeMockabilityOf(MockUtil.java:29)
    at org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
    at org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:186)
    at org.mockito.internal.creation.MockSettingsImpl.confirm(MockSettingsImpl.java:180)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:62)
    at org.mockito.Mockito.mock(Mockito.java:1729)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:33)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
    at org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)
    at org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:57)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)

My test was something as such:

import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import static org.mockito.MockitoAnnotations.initMocks;

@PrepareForTest(MyClass.class)
public class MyTest extends PowerMockTestCase {

    @BeforeTest
    public void init() {
        initMocks(this);
    }
}

As mentioned in this thread, removing the initMocks() method removes the error, but all the mocks become null.


✅ Solution: BeforeTest VS BeforeMethod

What I found out for my case is that @BeforeTest was actually posing a problem. Changing it to @BeforeMethod resolved the error.

import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import static org.mockito.MockitoAnnotations.initMocks;

@PrepareForTest(MyClass.class)
public class MyTest extends PowerMockTestCase {

    @BeforeMethod // CHANGE THIS!
    public void init() {
        initMocks(this);
    }
}

My guess is that it is something to do with beans injection; @BeforeTest is executed before any beans got injected while @BeforeMethod is executed after beans injection. Not sure how it really affected though.

Ely
  • 51
  • 1
  • 4
  • Do you have a solution without powermock? – portfoliobuilder Dec 14 '20 at 03:05
  • @portfoliobuilder if you're not using powermock, I don't think you will encounter the same issue I faced. Probably you could double check the other suggestions given on this thread? Make sure mockito is updated, that you're using jdk and you don't have the missing references. – Ely Dec 16 '20 at 09:14
5

In my case, after removing mockito-core, the test worked!

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>${mockito.version}</version>
    <scope>test</scope>
</dependency>

My version is here, and JDK is 1.8.0_121.

<properties>
    <powermock.version>2.0.7</powermock.version>
    <mockito.version>2.8.9</mockito.version>
</properties>

Now my dependencies are:

  • powermock-api-mockito2
  • powermock-module-junit4
Jess Chen
  • 3,136
  • 1
  • 26
  • 35
  • Same here. Best to avoid incompatibilities by using what the documentation says: https://github.com/powermock/powermock/wiki/Mockito-2-Maven – lauksas Dec 29 '21 at 13:11
  • Removing mockito-core is a great solution, it also works for Java17. To make it fully working, need add following inside of org.apache.maven.plugins --add-opens java.base/java.lang=ALL-UNNAMED ... ... – XLi Nov 11 '22 at 17:41
4

Remove version declaration works for me:

Example:

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.8.9</version>
        <scope>test</scope>
    </dependency>

remove 2.8.9

After:

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <scope>test</scope>
    </dependency>

It may due to version issue between jar packages of this dependency.

Hai Huang
  • 49
  • 1
  • you're surely inheriting the version because removing it will break the project. Wrong so wrong answer. – eduyayo Jun 28 '19 at 12:00
  • This was oddly the solution for me. I think this must be because of a parent pom, in my case `org.springframework.boot:spring-boot-starter-parent:2.4.0`. Trying to use a higher version of Mockito led to this strange error, but letting the parent pom's dependency management seemed to alleviate the issue. I had tried to use Mockito `4.8.1` but the dependency management dropped it back to `3.6.0`. Additionally, I read that there is some issue with IntelliJ and the 4.x version's use of byte-buddy. – jocull Nov 11 '22 at 03:29
  • I had the same issue using gradle. This is how I solved: `testImplementation 'org.mockito:mockito-core'` – Digao Nov 18 '22 at 20:05
4

For android development you need to import a couple of things:

 dependencies {
   testCompile "org.mockito:mockito-core:+"
   androidTestCompile "org.mockito:mockito-android:+"
 }

could not find any reference of this but this is the only one that has worked for me.

mel3kings
  • 8,857
  • 3
  • 60
  • 68
3

I had this problem when I was using mockitokotlin2. I solved it by using latest version of libraries:

testImplementation 'com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0'
testImplementation 'org.mockito:mockito-inline:4.4.0'
Joe Rakhimov
  • 4,713
  • 9
  • 51
  • 109
2

In my case, I was working on a project that does not use the maven build system. So this is what worked for me.

NB: (creating the library is optional, you can add the jars directly to your project build path)

Hope this helps someone.

Skelli
  • 283
  • 2
  • 10
2

I solved this problem by removing jmockit in POM XML for Maven. After that my Junit 5 tests work perfectly.

    <dependency>
        <groupId>org.jmockit</groupId>
        <artifactId>jmockit</artifactId>
        <version>1.41</version>
        <scope>test</scope>
    </dependency>

With this dependency I always get an error like:

java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)
...

Could not initialize inline Byte Buddy mock maker. (This mock maker is not supported on Android.)
...

Caused by: com.sun.tools.attach.AttachNotSupportedException: no providers installed
...
Guchelkaben
  • 1,205
  • 1
  • 12
  • 18
1

I had the same issue and tryed @Paskas's solution, worked well Junit Test ok at first. added the bytebuddy dependency to my pom.xml:

<dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy-dep</artifactId>
            <version>1.9.7</version>
</dependency>

Hope this helps.

  • I had the same issue and was also able to resolve by explicitly adding the latest ByteBuddy to the POM. Maven isn't resolving the transitive dependency correctly. See here: https://github.com/mockito/mockito/issues/2629 – martin_wun Jul 10 '23 at 06:47
1

I encountered this issue and solved it by bumping my version of org.mockito.mockito-core to the latest release. I had been using an older release for quite some time.

Adil B
  • 14,635
  • 11
  • 60
  • 78
1

Delete the "byte-buddy-1.7.11.jar" manually from the maven repository path which appears in the error. Maven update the project and the issue will be resolved. Tried and worked for me.

Arjun
  • 25
  • 5
1

Mockito 2 requires dependencies. Adding the two ByteBuddy dependencies below. solved the issue for me:

  • byte-buddy-x.x.xx.jar
  • byte-buddy-agent-x.x.xx.jar

In my case I include jar files in the project, which can be found at: https://bintray.com/raphw/maven/ByteBuddy/

If you need it for a Maven project, simply add:

<dependency>
  <groupId>net.bytebuddy</groupId>
  <artifactId>byte-buddy</artifactId>
  <version>1.9.14</version>
  <type>pom</type>
</dependency>
1

For me the problem was that IntelliJ ran the test as integration test. So I needed to create JUnit test manually

enter image description here

tonisives
  • 1,962
  • 1
  • 18
  • 17
  • Maybe you have this unit test in the androidTest directory? I presume AS expect to have instrumented tests in 'androidTest' and unit tests in 'test'. – Kikiwa Nov 20 '20 at 16:45
1

You're probably having issues with manually adding dependencies to your project. Take note of the mockito-core jar version being used in your project.

Visit this mvn repository link

https://mvnrepository.com/artifact/org.mockito/mockito-core/{replace-with-your-mockito-core-version}

Move to the compile dependencies sections down below in the mvn repository page, download all the appropriate version of the dependencies mockito-core needs.

As of answering this question:

byte-buddy

byte-buddy-agent

objenesis

Add all to the project together with mockito-core and run tests.

emma-ea
  • 324
  • 2
  • 5
1

I had same error, removing the dependency version for mockito core and doing a fresh mvn clean install fixed the error

brainynerd
  • 11
  • 1
0

in my case, some abnormal env setting will also lead to this error:

in ubuntu 16.04, java and javac had been update-alternatives to 7 but $JAVA_HOME had been wrongly set to 8

i remove the $JAVA_HOME, and everything back to normal

cfz
  • 33
  • 1
  • 7
0

I had the same exception when switch to Java 10 and Spring Boot 2. This dependency combination worked for me:

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>2.0.2-beta</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>net.bytebuddy</groupId>
        <artifactId>byte-buddy</artifactId>
        <version>1.8.16</version>
    </dependency>
    <dependency>
        <groupId>net.bytebuddy</groupId>
        <artifactId>byte-buddy-agent</artifactId>
        <version>1.8.16</version>
        <scope>test</scope>
    </dependency>
Svitlana Onish
  • 284
  • 3
  • 14
0

Adding a bnd aspect to this

Adding on to Paskas' answer, you also have to include the dependencies in the cnf maven repository, if you're using one (like my cnf/central.mvn).

org.mockito:mockito-core:2.21.0
net.bytebuddy:byte-buddy:1.8.15
net.bytebuddy:byte-buddy-agent:1.8.15
org.objenesis:objenesis:2.6

and for convenient referencing, you can include a bnd variable in your cnf/build.bnd

mockito: org.mockito:mockito-core; version=2.21.0,\
         net.bytebuddy:byte-buddy; version=1.8.15,\
         net.bytebuddy:byte-buddy-agent; version=1.8.15,\
         org.objenesis:objenesis; version=2.6

and in your project's bnd file

-testpath:\
    ${mockito}
Zymus
  • 1,673
  • 1
  • 18
  • 38
0

I have had the same problem in one existing project. I used java 8 and additionally installed java 10. So I started get this exception. I deinstalled java 10, it has not helped. I deleted bytebuddy jars from maven repo, it has not helped. Only after complete removal of all jars from maven repo I could compile project again.

Roman
  • 101
  • 7
0

Not the answer to the original poster, since s/he's using Netbeans, but in Eclipse I needed to do "Maven -> Update Project" in order to get tests working again.

Brimstedt
  • 3,020
  • 22
  • 32
0

It worked for me After I removed bytebuddy folder from ${home}.m2\repository\net\bytebuddy and removed byte-buddy-agent,byte-buddy and objenesis dependency from pom.xml

0

I had the same issue, got resolved by adding jcenter in repositories and mockito dependecies.

repositories {
    jcenter()
 }
 dependencies {
    testImplementation 'org.mockito:mockito-core:3.7.7'
    testImplementation 'org.powermock:powermock-core:1.7.4'
    testImplementation 'org.powermock:powermock-module-testng:1.7.4'
    testImplementation 'org.powermock:powermock-api-mockito2:1.7.4'
 }
  • 1
    JCenter is now [end of life](https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/) as of May 1, 2021. – Mr. Polywhirl May 03 '21 at 20:25
0
    androidTestImplementation 'org.mockito:mockito-core:2.19.0' 
testImplementation "org.mockito:mockito-core:2.19.0"//game changer for your question

This second line was a game-changer, android Test implementation and test implementation are not the same test set (android test implementation is a test set for physical devices or emulators)... you may have dependency for one and writing code, but if you run the different test (local in the android studio without emulator) it will fail (unless..:)

happy testing

Nenad Štrbić
  • 367
  • 4
  • 6
0

In my case, removing:

{home}/.m2/repository/org/robolectric/

solved the issue. Next time it runs, it will download those files again.

Lucas
  • 1,224
  • 1
  • 14
  • 21
0
  • PowerMock doesn't work with sonar in the first step, the cause of the problem is the combination of powermock and jacoco
  • We will not face this issue locally, but if we use sonar for test coverage calculations, the error is as follows
Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null) 
  • In PowerMock 2.0.9 version, a workaround for this problem is provided they have added an annotation @PrepareOnlyThisForTest, this provides the ability for the isolation of a particular Test class.
  • Apart from that, we need to add delegate the Runner to SpringRunner using @PowerMockRunnerDelegate(SpringRunner.class)

Add Power Mock Dependencies in pom.xml

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>

Use the PowerMock Junit Runner for test Class and declare the test class that we’re mocking and delegate SpringRunner

    @RunWith(PowerMockRunner.class)
    @PrepareOnlyThisForTest(ServiceApplication.class)
    @PowerMockRunnerDelegate(SpringRunner.class)
    public class ExampleControllerTest {
        PowerMockito.mockStatic(ServiceApplication.class);
        Mockito.when(ServiceApplication.getStatic()).thenReturn("");
0

I got the same issue, finally fix it.

It's a long answer, but if you struggling with this issue for a while, hope this can help you.


This is my scenario.

Android Unit Test

dependency

-> org.mockito:mockito-core ()

-> org.powermock:powermock-api-mockito2 (mock static class)

-> mockito-inline (enable final class mock)

-> com.nhaarman.mockitokotlin2:mockito-kotlin


Root Cause -> check the error log

Issue1 -> Tools.jar dependency missed

In order to use the mock-maker-inline (mockito-inline), it has dependency on Tools.jar. We need the dependency.

here is the link

My error log looks like below

java.lang.RuntimeException: Invoking the beforeTestMethod method on PowerMock test listener org.powermock.api.extension.listener.AnnotationEnabler@49a4bf9a failed.

...

Caused by:
        java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)

        ... 

        Caused by:
            java.lang.IllegalStateException: Failed to load interface org.mockito.plugins.MockMaker implementation declared in sun.misc.CompoundEnumeration@3d529098

            ...

            Caused by:
                java.lang.reflect.InvocationTargetException

                ...

               Caused by:
                    org.mockito.exceptions.base.MockitoInitializationException: 
                    Could not initialize inline Byte Buddy mock maker.
                    ...

                    Caused by:
                                java.lang.NullPointerException
                                    at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:182)

So you can see the last line says attachProvider throw NullPointerException, this attachProvider exists in the tools.jar

class path is com.sun.tools.attach.AttachProvider.

So we need to add the dependency for tools.jar


Issue2 -> added wrong dependency for tools.jar

I added a wrong dependency for tools.jar use the MacOS tools.jar as dependency.

But our build machine is Linux platform, So I got this error with diff error log.

Cause JDK has different version with different platforms (MacOS, Linux, Windows)
based on the different platforms `VirtualMachine` has diff implementation (MacOS, Linux, Windows) 

Here is the error log

Caused by:
        java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)

        ... 

        Caused by:
            java.lang.IllegalStateException: Failed to load interface org.mockito.plugins.MockMaker implementation declared in sun.misc.CompoundEnumeration@3d529098

            ...

            Caused by:
                java.lang.reflect.InvocationTargetException

                ...

               Caused by:
                    org.mockito.exceptions.base.MockitoInitializationException: 
                    Could not initialize inline Byte Buddy mock maker.
                    ...

                    Caused by:
                                java.lang.UnsatisfiedLinkError: sun.tools.attach.BsdVirtualMachine.getTempDir()Ljava/lang/String;
                                    at sun.tools.attach.BsdVirtualMachine.getTempDir(Native Method)
                                    at sun.tools.attach.BsdVirtualMachine.<clinit>(BsdVirtualMachine.java:308)
                                    at sun.tools.attach.BsdAttachProvider.attachVirtualMachine(BsdAttachProvider.java:63)
                                    at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:208)


You can see here, VirtualMachine find the AttachProvider (BsdAttachProvider) but after that it throw an exception.

So which means we added the dependency, but the dependency is wrong.


How to add the tools.jar dependency correctly

(1) add tools.jar file to lib folder (WRONG)

add this `testImplementation fileTree(dir: 'libs', include: ['tools.jar'])` in the gradle file

this is not a good approach, cause our build machine (remote) may use the Linux system, but our local machine (Laptop, PC) may use the MacOS or Windows.

this will cause the Issue2  which I mentioned above

(2) add testImplementation files(org.gradle.internal.jvm.Jvm.current().toolsJar) in gradle file. (WRONG)

this one will throw NullPointerException after gradle 4.X.

(3) add testImplementation files("${System.properties['java.home']}/../lib/tools.jar") in gradle file

it will trying to read the environment virable to get the path for the `tools.jar`

Cause both build machine (remote) and local machine (Laptop, PC) need to configure the JDK to make it work.

So this approach should find it's own path even it's based on diff platform (MacOS, Linux, Windows)

This is the approach I am using, If you have better one, please let me know.

Configure Android Studio JDK Location

Don't use the Android Studio Application folder as the JDK location.

Use the JAVA_HOME variable path as the JDK location. (you can type echo JAVA_HOME in the terminal)

Otherwise when you run the unit test it will show this error

Transform's input file does not exist: /Applications/Android Studio.app/Contents/jre/jdk/Contents/lib/tools.jar.

Cause it's Android Studio Application JDK folder doesn't have the tools.jar file. (you can compare the normal configured JDK folder with Android Studio Application Package one)

/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home

After these steps, you should be able to run the unit test.

If you got this org.mockito.exceptions.misusing.NotAMockException when running the unit test

please make sure the mocktio-inline configured correctly.

The issue link (https://github.com/powermock/powermock/issues/992)

Based on the mockito documents (https://github.com/powermock/powermock/wiki/mockito#mockito-mock-maker-inline)

It provides two approaches

  1. org.mockito.plugins.MockMaker

  2. org/powermock/extensions/configuration.properties

Just try these two approaches, check which one work for you, and just keep one of them.

In my scenario second one works for me.

I also tried this old approach testImplementation 'org.mockito:mockito-inline:X.X.X' it not work for me.

Jeffery Ma
  • 3,051
  • 1
  • 23
  • 26
  • About the diff between `java.home` and `java_home` here is the [link](https://stackoverflow.com/a/11345708/4593755) – Jeffery Ma Jul 27 '21 at 09:22
0

If you use e.g. a different version of spring-boot-test, you might have a bytebuddy version conflict, as mentioned above. To fix, you can use dependencyManagement:

<dependencies>
  <dependency>
     <groupId>org.mockito</groupId>
     <artifactId>mockito-core</artifactId>
     <version>3.11.2</version>
     <scope>test</scope>
  </dependency>
</dependencies>
<dependencyManagement>
  <dependencies>
     <dependency>
        <groupId>net.bytebuddy</groupId>
        <artifactId>byte-buddy</artifactId>
        <version>1.11.10</version>
     </dependency>
     <dependency>
        <groupId>net.bytebuddy</groupId>
        <artifactId>byte-buddy-agent</artifactId>
        <version>1.11.10</version>
     </dependency>
  </dependencies>
</dependencyManagement>
serv-inc
  • 35,772
  • 9
  • 166
  • 188
0

Thanks @Łukasz Rzeszotarski for his solving - it works for me. I just want to add several details about this problem.

This problem appears when i include mockito-inline in my gradle-project, but i don't can refuse of it. It has appear because mockito-inline has follows structure:

META-INF:
    MANIFEST.MF
mockito-exstensions:
    org.mockito.plugins.MockMaker
    org.mockito.plugins.MemberAccessor

where the file org.mockito.plugins.MockMaker contains:

mock-maker-inline

This string is needs for mocking final classes and methods and it causes problems, when you using JRE instead of JDK.

Zhenyria
  • 376
  • 1
  • 16
  • Yo mean, definiing the gradle build tools - java, using jre normally included in Android Studio instead of a jdk version? – htafoya Mar 02 '22 at 03:39
0

I had a problem with the same exception, but mine came with some additional info. For me this issue was specifically within android studio and included the following:

Caused by: java.io.IOException: Cannot run program ""/Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java""

it turned out that apparently this library does not handle whitespace in the path, and I had to rename my "Android Studio" instance to "AndroidStudio"

AdamWardVGP
  • 670
  • 1
  • 5
  • 13
0

I had the same problem, in my case, the cause is because of the wrong version of the byte-buddy. That was triggered by maven dependency duplication. The duplicate dependency overwrites the higher version of byte-buddy with a lower version making a problem.

Recap(in my case):

  1. net.bytebuddy:byte-buddy-agent:jar:1.9.3 should have worked but was overwritten by net.bytebuddy:byte-buddy:jar:1.7.9 from a duplicate dependency which caused my problem.

solution:

  1. check the maven dependency with the code below:
mvn dependency:tree -Dverbose
  1. if you found something like below:
[INFO] |  +- org.mockito:mockito-core:jar:2.23.4:test
[INFO] |  |  +- (net.bytebuddy:byte-buddy:jar:1.9.3:compile - scope updated from test; omitted for duplicate)
[INFO] |  |  +- net.bytebuddy:byte-buddy-agent:jar:1.9.3:test
...
[INFO] +- io.springfox:springfox-core:jar:2.8.0:compile
[INFO] |  +- net.bytebuddy:byte-buddy:jar:1.7.9:compile

you can exclude the duplicate lower version of byte-buddy on pom.xml like below(which is my case):

<groupId>io.springfox</groupId>
<artifactId>springfox-core</artifactId>
<version>2.8.0</version>
<exclusions>
    <exclusion>
        <groupId>net.bytebuddy</groupId>
        <artifactId>byte-buddy</artifactId>
    </exclusion>
</exclusions>
William
  • 11
  • 4
0

In my case I tried aligning the versions of mockito and byte buddy but I still got the error. I did a mvn dependency:tree command to look through all the dependencies and I found some proprietary packages from my organisation that included powermock and mockito dependencies. After excluding those dependencies the error disappeared

0

Find out the mockito core version your project.

Note down the correct dependent version of byte-buddy and include in the project. If the jar is already included with some other version, override the version with this correct version.

Minoltan
  • 1
  • 1
  • 1
-1

Just update to the latest release of org.mockito:mockito-core. Once I did, the errors disappeared!

Huw Davies
  • 791
  • 7
  • 19