Mockito cannot mock this class: interface
Asked Answered
F

9

11

I'm having an issue with mockito and powermock, I can mock an abstract class with a final static method with no problems. When trying to mock an Interface as with WebIServerSession I'm getting the stacktrace below. I've had a look at other issues in powermock github repo and it seems to be related with the jvm version. I've already upgraded to the latest 1.8 java version as stated in https://github.com/mockito/mockito/issues/636 and I'm still getting the same error. Might it be related with Powermock compatibility with Mockito 2?

import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

@BeforeMethod
public void setup() throws Exception {
    mockStatic(ResourceBundle.class);
    mockStatic(WebObjectsFactory.class);
    WebObjectsFactory webObjectsFactory = mock(WebObjectsFactory.class);
    WebIServerSession webIServerSession = mock(WebIServerSession.class);

    PowerMockito.when(WebObjectsFactory.getInstance()).thenReturn(webObjectsFactory);
    PowerMockito.when(webObjectsFactory.getIServerSession()).thenReturn(webIServerSession);
    whenNew(ThreadLocal.class).withNoArguments().thenReturn(errorContainer);

    MockitoAnnotations.initMocks(this);
}


@Test
public void shouldBeTrue() {
    assertTrue(true);
}

Maven dependencies:

<dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.14.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.8.9</version>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-core</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-testng</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-reflect</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Stacktrace:

org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: interface com.microstrategy.web.objects.WebIServerSession.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.


Java               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.191-b12
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0_191-b12
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.14.1


Underlying exception : java.lang.IllegalArgumentException: Could not create type

    at com.myproject.SSOESMTest.setup(SSOESMTest.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:458)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:523)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.IllegalArgumentException: Could not create type
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
    at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:50)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:116)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
    ... 28 more
Caused by: java.lang.NoClassDefFoundError: com/microstrategy/utils/xml/SAXSupport
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.getDeclaredMethods(Class.java:1975)
    at net.bytebuddy.description.method.MethodList$ForLoadedMethods.<init>(MethodList.java:109)
    at net.bytebuddy.description.type.TypeDescription$ForLoadedType.getDeclaredMethods(TypeDescription.java:8426)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.getDeclaredMethods(TypeDescription.java:3654)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:634)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:596)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:632)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:567)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:465)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:463)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:198)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:189)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3394)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3583)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
    ... 39 more
Caused by: java.lang.ClassNotFoundException: com.microstrategy.utils.xml.SAXSupport
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 63 more


Test ignored.

===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 2
===============================================


Process finished with exit code 0
Farthing answered 8/11, 2018 at 13:48 Comment(5)
I think the message is clear Mockito can only mock non-private & non-final classesFerwerda
That's why I'm using powermock. That error is not completely accurate. Something is wrong in my setup or there is an issue with one of the libraries I'm using I guess..Farthing
Please Show importsFerwerda
There you go...Farthing
Looks like the main Problem is: Caused by: java.lang.ClassNotFoundException: com.microstrategy.utils.xml.SAXSupportFerwerda
F
13

The exception is most likely to occur due to the version of Mockito used.

Try by replacing the current version of mockito-core with below dependency.

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

Ignore the warning of overriding managed version in pom.xml

Fullrigged answered 1/7, 2020 at 11:41 Comment(1)
Why? And, how long will we use an old version?Thumping
S
5

Make sure your interface visibility is public.

I am not sure that it will be the solution in your case. I got the same issue when I was testing in Android Studio.

My solution was replace core-mockito with

androidTestImplementation "org.mockito:mockito-android:2.25.0"

Then it started working perfect.

It may be solution for those who are testing for Android Studio and having the same issue.

Solicitude answered 27/6, 2019 at 20:4 Comment(1)
I am using 2.28.2 version and it is still the same problemEstriol
S
4

add

@RunWith(MockitoJUnitRunner.class)
Shebashebang answered 29/5, 2019 at 7:8 Comment(1)
Note that the Runner can not be used with JUnit 5, use Extension instead. #40961557Broadcloth
A
2

I had a similar issue. I was surprisingly having:

Mockito cannot mock this class: interface javax.servlet.ServletContext.

This was only when I ran my test in my IDE (IntelliJ Idea). If I tried to run it via maven command - it passed. To make the test work in IntelliJ Idea I just changed the configurations: Set Shorten command line to JAR manifest.

Abdella answered 9/12, 2020 at 18:12 Comment(1)
This solved my issue as well! I had been using shorten command line: classpath file, and needed to switch to jar manifest.Indulgence
S
1

I also experienced this problem when trying to mock a non-public interface, and the error message didn't make sense, as all my tests in another suite passed correctly while mocking the same interface.

In my case I had to downgrade the Mockito Core library and revert it again to make it work. Here are the steps I took:

  1. Find the Mockito Core dependency in the module level build.gradle file entry:
    testImplementation 'org.mockito:mockito-core:2.25.0'
  1. Downgrade to another valid version, in my example 2.23.0:
    testImplementation 'org.mockito:mockito-core:2.23.0'
  1. Do a Gradle sync and wait for completion
  2. Revert the Mockito Core dependency to the same version you had before (or newer):
    testImplementation 'org.mockito:mockito-core:2.25.0'
  1. Sync the project again
  2. Run the tests again
Splenic answered 12/2, 2020 at 22:46 Comment(0)
H
0

It's Strange but after adding below line in build.gradle file it work for me

androidTestImplementation "org.mockito:mockito-android:$mockitoAndroid"
Hy answered 1/2, 2021 at 13:35 Comment(0)
B
0

I also have this problem by using IDEA, finally choose Shorten command line: "JAR manifest" solved

Breakup answered 18/3, 2022 at 10:9 Comment(0)
F
0

In my case it was interface, I was mocking using Mockito library.

After adding below dependency, I am able to mock and test properly.

testImplementation("org.mockito:mockito-inline:4.0.0")

mockito-inline - moreInfo

Flowage answered 21/10, 2023 at 13:23 Comment(0)
F
-1

annotate your test class like this

@RunWith(PowerMockRunner.class)
@PrepareForTest({ResourceBundle.class, WebObjectsFactory.class, AnyOtherClassThatContainsStaticMethod.class, . . .})

ref: https://github.com/powermock/powermock/wiki/mockstatic

Febrile answered 30/5, 2019 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.