Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito object is not an instance of declaring class

Tags:

java

mockito

I haven't touched Mockito for a while, and I have never used it extensively. But today in some new code I wanted to use best practices so I pulled out mockito-core 2.0.54-beta using the following Java version:

java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)

I needed an instance of this interface for testing:

https://bitbucket.org/globalmentor/rincl/src/bf0e8875a1bae16247dd904e0b8bc067c9f8abc9/src/main/java/io/rincl/ResourceI18nConcern.java

public interface ResourceI18nConcern extends Concern {

    public Locale getLocale(@Nonnull Locale.Category category);

    public void setLocale(@Nonnull Locale.Category category, @Nonnull Locale locale);

    public default void setLocale(@Nonnull Locale locale) {...}

    public Resources getResources(@Nonnull final Class<?> contextClass) throws ResourceConfigurationException;

}

That interface extends this one (just an empty marker interface):

https://bitbucket.org/globalmentor/csar/src/125b837e9936ddb8d6340fa99b6b5da872d1e6e5/src/main/java/io/csar/Concern.java

In my test I tried to do this simple thing:

final ResourceI18nConcern defaultConcern=mock(ResourceI18nConcern.class);

I get the following stack trace:

org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface io.rincl.ResourceI18nConcern

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

Underlying exception : java.lang.IllegalArgumentException: object is not an instance of declaring class
    at io.rincl.RinclTest.defaultConcernRinclGetLocaleIsConcernLocale(RinclTest.java:91)
    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:483)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
    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:483)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3875)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator$Chained.resolve(TypeDescription.java:3501)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3834)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator.asList(TypeDescription.java:3477)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfWildcardType$ForLoadedType.getDeclaredAnnotations(TypeDescription.java:4771)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onWildcard(TypeDescription.java:676)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onWildcard(TypeDescription.java:659)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfWildcardType.accept(TypeDescription.java:4679)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onParameterizedType(TypeDescription.java:687)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onParameterizedType(TypeDescription.java:659)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfParameterizedType.accept(TypeDescription.java:5021)
    at net.bytebuddy.description.type.TypeDescription$Generic$LazyProjection.accept(TypeDescription.java:5794)
    at net.bytebuddy.description.method.ParameterDescription$TypeSubstituting.getType(ParameterDescription.java:866)
    at net.bytebuddy.description.method.ParameterList$AbstractBase.asTypeList(ParameterList.java:85)
    at net.bytebuddy.description.method.MethodDescription$AbstractBase.asTypeToken(MethodDescription.java:635)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Harmonized.of(MethodGraph.java:862)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Store.registerTopLevel(MethodGraph.java:1059)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:569)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:529)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:565)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:502)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:423)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:489)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:153)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2564)
    at org.mockito.internal.creation.bytebuddy.MockBytecodeGenerator.generateMockClass(MockBytecodeGenerator.java:60)
    at org.mockito.internal.creation.bytebuddy.CachingMockBytecodeGenerator$CachedBytecodeGenerator.generate(CachingMockBytecodeGenerator.java:72)
    at org.mockito.internal.creation.bytebuddy.CachingMockBytecodeGenerator$CachedBytecodeGenerator.getOrGenerateMockClass(CachingMockBytecodeGenerator.java:64)
    at org.mockito.internal.creation.bytebuddy.CachingMockBytecodeGenerator.get(CachingMockBytecodeGenerator.java:27)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createProxyClass(ByteBuddyMockMaker.java:54)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:27)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:32)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:54)
    at org.mockito.Mockito.mock(Mockito.java:1443)
    at org.mockito.Mockito.mock(Mockito.java:1356)
    ... 26 more

Am I doing something wrong? This seemed to me as if it should be straightforward.

To reproduce this problem, clone https://bitbucket.org/globalmentor/rincl.git and check out commit 2f88d7c5e5ac17b6d316ed54c12cb7b447b7d6ac. Then try to run the following test:

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import java.util.Locale;
import java.util.Locale.Category;
import org.junit.*;

public class RinclTest {
    @Test
    public void defaultConcernRinclGetLocaleIsConcernLocale() {
        final ResourceI18nConcern defaultConcern=mock(ResourceI18nConcern.class);
    }
}
like image 623
Garret Wilson Avatar asked May 30 '16 13:05

Garret Wilson


People also ask

Why is Mockito not working with Java 11?

Worked for me. It is because of Java/Mockito compatibility. For example, if you are using Java 11 with Mockito 2.17.0, it will throw the same error (Upgrading to Mockito 2.22.0 or later will solve it). Aside from digging into their release artifact on Github, I am yet to see a comprehensive document that spells out the compatibility matrix.

How does InjectMocks work with Mockito?

Anyone who has used Mockito for mocking and stubbing Java classes, probably is familiar with the InjectMocks -annotation. Use this annotation on your class under test and Mockito will try to inject mocks either by constructor injection, setter injection, or property injection. This magic succeeds, it fails silently or a MockitoException is thrown.

How to fix the Mockito dependency in Maven?

Fixed by excluding that transitive Mockito dependency and re-adding it explicitly with version 2.23.4 (and re-build if not done automatically). Snippet of my maven POM:

Can we write unit tests for a class with object instantiation?

With this trick, we can write unit tests even for classes that have object instantiations in their implementation. Given that implementing the factory pattern is not feasible or not worth the effort.


Video Answer


2 Answers

Your Java runtime version is from March 2014; plenty of bugs have been fixed in the VM ever since and you should really upgrade. I am 99% sure that this problem is related to type annotations (@NonNull) which were introduced in this version for the first time in this exact release. I am sure that your problem will go away if you upgrade your VM.

I can successfully execute your proposed test with a recent build of the HotSpot VM.

like image 182
Rafael Winterhalter Avatar answered Oct 21 '22 10:10

Rafael Winterhalter


Had the same issue with my project and used the Rincl project above to confirm I was having the same issue. Using JDK 1.8.0_11 on Mac the reported errors were the same as Garret. Updating to version JDK 1.8.0_181 I ran the Rincl test with NO errors. Apparently Mockito is using the latest of the JDK 1.8.0.

like image 4
dqromney Avatar answered Oct 21 '22 11:10

dqromney