Mockito kann diese Klasse nicht verspotten

Lesezeit: 8 Minuten

Ich versuche, eine öffentliche Klasse zu verspotten, aber Mockito wirft dabei eine Mockito cannot mock this class Ausnahme.

Klasse, die ich verspotten möchte: https://github.com/scribejava/scribejava/blob/master/scribejava-core/src/main/java/com/github/scribejava/core/builder/ServiceBuilder.java

Testcode:

package xyz.jacobclark.adapter;

import com.github.scribejava.apis.TwitterApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.oauth.OAuth10aService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.io.IOException;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsInstanceOf.any;

@RunWith(MockitoJUnitRunner.class)
public class TwitterOAuthAdapterTest {
    @Mock
    ServiceBuilder serviceBuilder;

    @Test
    public void getRequestTokenShouldReturnAValidRequestToken() throws IOException {
        class TwitterOAuthAdapter {
            private final OAuth10aService service;

            public TwitterOAuthAdapter(ServiceBuilder serviceBuilder){
                this.service = serviceBuilder
                    .apiKey("")
                    .apiSecret("")
                    .build(TwitterApi.instance());
            }

            public OAuth1RequestToken getRequestToken() throws IOException {
                return this.service.getRequestToken();
            }
        }

        TwitterOAuthAdapter oAuthAdapter = new TwitterOAuthAdapter(serviceBuilder);
        Assert.assertThat(oAuthAdapter.getRequestToken(), is(any(OAuth1RequestToken.class)));
    }
}

Vollständiger Stacktrace:

xyz.jacobclark.adapter.TwitterOAuthAdapterTest

org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class com.github.scribejava.core.builder.ServiceBuilder.

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.0-b70
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0-b132
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.11.3


Underlying exception : java.lang.IllegalArgumentException: object is not an instance of declaring class

    at org.mockito.internal.runners.SilentJUnitRunner$1.withBefores(SilentJUnitRunner.java:29)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
    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.mockito.internal.runners.SilentJUnitRunner.run(SilentJUnitRunner.java:39)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:103)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
    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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
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:3843)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator$Chained.resolve(TypeDescription.java:3468)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3803)
    at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator.asList(TypeDescription.java:3439)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfWildcardType$ForLoadedType.getDeclaredAnnotations(TypeDescription.java:4748)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onWildcard(TypeDescription.java:680)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onWildcard(TypeDescription.java:663)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfWildcardType.accept(TypeDescription.java:4656)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onParameterizedType(TypeDescription.java:691)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing.onParameterizedType(TypeDescription.java:663)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfParameterizedType.accept(TypeDescription.java:4998)
    at net.bytebuddy.description.type.TypeList$Generic$AbstractBase.accept(TypeList.java:249)
    at net.bytebuddy.description.type.TypeDescription$Generic$Visitor$TypeVariableErasing$RetainedTypeVariable.getUpperBounds(TypeDescription.java:832)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable.asErasure(TypeDescription.java:5373)
    at net.bytebuddy.description.method.MethodDescription$AbstractBase.asTypeToken(MethodDescription.java:701)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Harmonized.of(MethodGraph.java:881)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default$Key$Store.registerTopLevel(MethodGraph.java:1074)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:588)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:548)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyzeNullable(MethodGraph.java:567)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:581)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:521)
    at net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:442)
    at net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:480)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:160)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:153)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2568)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2670)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:84)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$CachedBytecodeGenerator.getOrGenerateMockClass(TypeCachingBytecodeGenerator.java:91)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:38)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:67)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:38)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:26)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)
    at org.mockito.Mockito.mock(Mockito.java:1637)
    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.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:39)
    at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:63)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:59)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:43)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:67)
    ... 23 more


Test ignored.
Process finished with exit code 255

  • hast du dir stackoverflow.com/questions/37527038/… angesehen? es sagt, dass es möglicherweise mit Ihrer Java-VM-Version zusammenhängt

    – uylmz

    8. Dezember 2016 um 22:39 Uhr

  • Ich habe aktualisiert, aber kein Glück.

    – Jacob Clark

    8. Dezember 2016 um 22:47 Uhr

  • Dies ist ein sehr interessantes Problem. Machen Sie etwas Interessantes mit Ihren Klassen oder Tests, wie das dynamische Laden aus einem JAR? (Oder gibt es einen anderen Grund, warum Sie zwei unterschiedliche Classloader im selben Test verwenden würden?)

    – Jeff Bowmann

    9. Dezember 2016 um 3:34 Uhr

  • Ein mögliches Duplikat des Mockito-Objekts ist keine Instanz der deklarierenden Klasse

    – Koraktor

    28. Februar 2017 um 21:46 Uhr

Obwohl es die Frage nicht speziell beantwortet (Frage ist Java 8), bin ich über Google hierher gekommen. Mit Java 11 habe ich dieses Problem gelöst, indem ich die folgende Abhängigkeit in aufgenommen habe build.gradle:

compile group: 'org.mockito', name: 'mockito-core', version: '2.22.0'

wie hier besprochen

  • Siehe Lösung unter dev.to/scottshipp/…. Hat für mich funktioniert.

    – Gopal Bairwa

    2. Februar 2020 um 17:47 Uhr

Dies liegt an der Java/Mockito-Kompatibilität. Wenn Sie beispielsweise Java 11 mit Mockito 2.17.0 verwenden, wird derselbe Fehler ausgegeben (ein Upgrade auf Mockito 2.22.0 oder höher löst ihn). Abgesehen davon, in ihre zu graben Artefakt auf Github veröffentlichen, ich muss noch ein umfassendes Dokument sehen, das die Kompatibilitätsmatrix darlegt. Hier ist eine hilfreiche Kompatibilitätsmatrix (basierend auf Schnelltest)

  • Mockito * – 2.17.0 => Java 8

(Fußnote: * – weiß nicht wie weit zurück)

  • Mockito 2.18.0 – 3.2.4 => Java 11

Hatte das gleiche Problem. Als ich meine Java JDK-Version auf 1.8.0_131 aktualisierte, verschwand der Fehler.

Benutzeravatar von nkadu1
nkadu1

Ich hatte das gleiche Problem. Ich habe alles versucht, was im Stapelüberlauf aufgeführt ist, dh

  • aktualisierte JDK-Version
  • Maven aktualisiert
  • ByteBuddy und Mockito zur Verwendung kompatibler Versionen gemacht.
  • Cache gelöscht
  • Verwenden Sie die neuesten Mockito-Versionen usw

und das : https://github.com/mockito/mockito/issues/1606.

Aber nichts hat bei mir funktioniert.

Ich habe den gesamten Cache gelöscht und dann Android Studio neu installiert, wodurch das Problem behoben wurde.

Wahrscheinlich hätte auch das Löschen aller Caches, die Android Studio verwendet, das Problem lösen können.

Als ich den Abhängigkeitsbaum meines Java-8-Projekts untersuchte, stellte ich fest, dass spring-boot-starter-test Mockito 2.15.0 verwendete. Behoben durch Ausschließen dieser transitiven Mockito-Abhängigkeit und explizites erneutes Hinzufügen mit Version 2.23.4 (und Neuerstellung, falls dies nicht automatisch erfolgt). Ausschnitt meines maven POM:

<dependencies>
...
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.23.4</version>
</dependency>
</dependencies>

Wenn Sie Gradle verwenden, sieht es ungefähr so ​​​​aus:

dependencies {
    ...
    def withoutMockito = {
        exclude group: 'org.mockito', module: 'mockito-core'
    }
    testImplementation "org.springframework.boot:spring-boot-starter-test:2.0.2-RELEASE", withoutMockito
    testImplementation "org.mockito:mockito-core:2.23.4"
 }

Benutzeravatar von wuxinshui
Wuxinshui

Ich hatte das gleiche Problem.

meine jdk-version ist 11.0.4+10-LTS.

ich benutze org.springframework.boot:spring-boot-starter-parent:2.0.7.RELEASE

Ich aktualisiere Mockito auf 3.3.0

Die Ausnahme passiert immer noch.

Dann habe ich das gemacht:

  1. Ausschluss von Mockito-Core aus dem Spring-Boot-Starter-Test

  2. unten zur pom-Datei hinzufügen

       <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>3.3.0</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>net.bytebuddy</groupId>
                    <artifactId>byte-buddy</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>net.bytebuddy</groupId>
                    <artifactId>byte-buddy-agent</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy</artifactId>
            <version>1.10.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy-agent</artifactId>
            <version>1.10.5</version>
            <scope>test</scope>
        </dependency>

Benutzeravatar von Jason Hartley
Jason Hartley

Datei -> Caches ungültig machen / Neustart

Geben Sie hier die Bildbeschreibung ein

Meine Klasse war öffentlich und nicht final. Das hat funktioniert.

1431200cookie-checkMockito kann diese Klasse nicht verspotten

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy