当前位置: 首页 > 知识库问答 >
问题:

Mockito不能模拟这个类

齐驰
2023-03-14

我试图模拟一个公共类,但是当这样做时,Mockito抛出一个Mockito不能模拟这个类异常。

我想嘲弄的班级:https://github.com/scribejava/scribejava/blob/master/scribejava-core/src/main/java/com/github/scribejava/core/builder/ServiceBuilder.java

测试代码:

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)));
    }
}

完整堆栈跟踪:

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

共有3个答案

韩靖琪
2023-03-14

我也有同样的问题。当我将Java JDK版本更新为1.8时。0_131错误消失。

徐茂材
2023-03-14

这是因为Java/Mockito的兼容性。例如,如果您将Java11与Mockito2.17一起使用。0时,将抛出相同的错误(升级到Mockito 2.22.0或更高版本将解决此问题)。除了在Github上挖掘他们的发布工件之外,我还没有看到一个详细说明兼容性矩阵的全面文档。下面是一个有用的兼容性矩阵(基于快速测试)

  • 莫基托*-2.17。0 =

(脚注:——不知道有多远)

  • 莫基托2.18。0 - 3.2.4 =
何兴学
2023-03-14

尽管它没有明确回答这个问题(问题是Java8),但我是通过谷歌来到这里的。使用Java11,我通过在build中包含以下依赖项解决了这个问题。格雷德尔

编译组:'org。mockito',名称:'mockito core',版本:'2.22。0'

正如这里所讨论的

 类似资料:
  • 我正在尝试在我的Spring启动应用程序中测试一个服务类。服务类中注入了bean。但是当我试图在我的测试类中模拟这个bean时,我遇到了问题。在测试用例中出现以下错误: 测试类看起来像这样: //没有什么花哨的,只是简单的验证保存方法被调用 我所尝试的: Mockito无法模仿这个类 将mockito内联版本更新为较新/较旧版本 使用的依赖项: mockito-inline::3

  • 我被通缉了,但没有被征召。方法在行处与此模拟错误没有任何交互。甚至我也嘲弄了这个对象&在调试函数时被调用。 下面是我要测试的函数,

  • 我在使用Mockito时遇到了麻烦,因为当我测试另一个时,我不能嘲笑第三类的属性。 我正在测试的类: 上一个类中使用的接口: 服务的真正实现: 由于gatewayProxyInvoker属性为null而引发NullPointerException的类: 测试等级: 属性“gate wayProxyInvoker”为空,因此我认为我在嘲笑它的过程中做错了什么。 代码运行良好,是我的JUnit测试不起

  • 当我尝试用PowerMock和Mockito测试一个方法并模拟它的依赖关系时遇到了问题。我尝试将依赖关系方法转换为非静态方法,并使用@mock注释和@injectmocks,但没有任何结果。 下面是正在测试的类和方法: 这里有一个我想要嘲弄的依赖关系,我很难嘲弄它: 最后,但不是最不重要的是,使用失败的测试方法的测试类。我不得不说,它甚至没有到达assert方法调用,而是在when().ThenR

  • 基类 在派生类中不应用组合和其他函数。如果是,我是否应用了错误的模式?我应该如何处理相同的?