Mockito 无法模拟此 class(人工 BuildInfo)

Mockito cannot mock this class (artifactory BuildInfo)

我正在尝试模拟一个 public class BuildInfo 但 Mockito 抱怨它不能。我安装了 java 11 JDK。被测代码是 Jenkins 共享库的一部分。

这是我的测试 class 的样子

import org.jfrog.hudson.pipeline.common.types.ArtifactoryServer
import org.jfrog.hudson.pipeline.common.types.buildInfo.BuildInfo
import org.junit.Test
import static org.mockito.Mockito.*
import org.jfrog.hudson.pipeline.scripted.dsl.ArtifactoryPipelineGlobal

class ArtifactoryLib extends BaseTest {
    @Override
    void setUp() throws Exception {
        super.setUp()

        ArtifactoryPipelineGlobal artifactory = mock(ArtifactoryPipelineGlobal.class)
        when(artifactory.newServer(anyMap())).thenReturn(mock(ArtifactoryServer.class))
        when(artifactory.newBuildInfo()).thenReturn(mock(BuildInfo.class))
        binding.setVariable("Artifactory", artifactory)
    }

    @Test
    void someTest() {
        def server = Artifactory.newServer url:url, credentialsId: credentialsId
        binding.getVariable("artifactorylib").doSomething("abc")
    }
}

我的测试代码正在执行如下操作:

void upload(String spec, int retention, def server) {
    // Artifactory here is of type ArtifactoryPipelineGlobal
    def buildInfo = Artifactory.newBuildInfo()
    buildInfo.retention([:])
}
void doSomething(String project) {
    // Artifactory here is of type ArtifactoryPipelineGlobal
    def server = Artifactory.newServer(url:"URL_HERE")
    upload("abc", 123, server)
}

我的 build.gradle 如下所示:

import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent

group 'jenkins-shared-library'
version '1.0-SNAPSHOT'

apply plugin: 'groovy'
apply plugin: 'idea'

sourceCompatibility = 11
targetCompatibility = 11

idea {
    module {
        downloadJavadoc = true
        downloadSources = true
    }
}

...

repositories {
    jcenter()
    mavenCentral()
    maven { url 'https://repo.jenkins-ci.org/releases/' }
}

dependencies {
    // Test frameworks
    implementation group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.5.13'
    testImplementation group: 'junit', name: 'junit', version: '4.13.1'
    testImplementation group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3'
    testImplementation group: 'com.lesfurets', name: 'jenkins-pipeline-unit', version: '1.3'
    testImplementation group: 'org.mockito', name: 'mockito-core', version: '3.5.11'

    // Jenkins plugins
    ...
    implementation group: 'org.jenkins-ci.plugins', name: 'artifactory', version: '3.8.1', ext: 'jar'
    implementation group: 'org.jfrog.buildinfo', name: 'build-info-api', version: '2.13.9', ext: 'jar'
    implementation group: 'org.jfrog.buildinfo', name: 'build-info-extractor', version: '2.13.9', ext: 'jar'

    // TRICKY: The lib folder contains all other plugins *JAR* files if not found in Maven
    implementation fileTree(dir: 'lib', include: ['*.jar'])
}

当运行命令./gradlew clean test时,出现以下错误

Mockito cannot mock this class: class org.jfrog.hudson.pipeline.common.types.buildInfo.BuildInfo.

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               : 11
JVM vendor name    : AdoptOpenJDK
JVM vendor version : 11.0.3+7
JVM name           : OpenJDK 64-Bit Server VM
JVM version        : 11.0.3+7
JVM info           : mixed mode
OS name            : Linux
OS version         : 4.15.0-112-generic


Underlying exception : java.lang.IllegalArgumentException: Could not create type
org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class org.jfrog.hudson.pipeline.common.types.buildInfo.BuildInfo.

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               : 11
JVM vendor name    : AdoptOpenJDK
JVM vendor version : 11.0.3+7
JVM name           : OpenJDK 64-Bit Server VM
JVM version        : 11.0.3+7
JVM info           : mixed mode
OS name            : Linux
OS version         : 4.15.0-112-generic


Underlying exception : java.lang.IllegalArgumentException: Could not create type
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:55)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:196)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callStatic(AbstractCallSite.java:208)
    at Artifactorylib.setUp(Artifactorylib.groovy:17)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.RunBefores.invokeMethod(RunBefores.java:33)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:258)
    at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access0(ParentRunner.java:66)
    at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:412)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:834)
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:36)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:77)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:43)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:29)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:52)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:61)
    at org.mockito.Mockito.mock(Mockito.java:1949)
    at org.mockito.Mockito.mock(Mockito.java:1860)
    at org.mockito.Mockito$mock.callStatic(Unknown Source)
    ... 57 more
Caused by: java.lang.NoClassDefFoundError: org/jfrog/build/extractor/clientConfiguration/deploy/DeployDetails$PackageType
    at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3166)
    at java.base/java.lang.Class.getDeclaredMethods(Class.java:2309)
    at net.bytebuddy.description.method.MethodList$ForLoadedMethods.<init>(MethodList.java:109)
    at net.bytebuddy.description.type.TypeDescription$ForLoadedType.getDeclaredMethods(TypeDescription.java:8687)
    at net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.getDeclaredMethods(TypeDescription.java:3736)
    at net.bytebuddy.description.type.TypeDescription$Generic$LazyProjection.getDeclaredMethods(TypeDescription.java:6203)
    at net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy$Default.doExtractConstructors(ConstructorStrategy.java:175)
    at net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy$Default.extractConstructors(ConstructorStrategy.java:196)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.applyConstructorStrategy(SubclassDynamicTypeBuilder.java:243)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:213)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:204)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3595)
    at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3819)
    at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:199)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.call(TypeCachingBytecodeGenerator.java:46)
    at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.call(TypeCachingBytecodeGenerator.java:43)
    at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
    ... 69 more
Caused by: java.lang.ClassNotFoundException: org.jfrog.build.extractor.clientConfiguration.deploy.DeployDetails$PackageType
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 87 more

请注意,模拟以下模拟工作 mock(ArtifactoryPipelineGlobal.class)mock(ArtifactoryServer.class) mock(BuildInfo.class)

原来我使用的是 JCenter 站点来获取工件依赖项。一旦我切换到 JFrog site,一切正常。