Byte-buddy 和 cglib 在 Spock 测试中不可用

Byte-buddy and cglib not available in Spock test

我开始使用 Spock 测试框架,我的 build.gradle 依赖项部分如下所示:

dependencies {
    testCompile "org.spockframework:spock-core:1.3-groovy-2.5"
}

我有一个(无用的)Spock 测试需要创建存根:

def 'A test that will fail'() {
    given: ''
    def random = Stub(Random)
}

启动后,测试失败并出现给定错误:

CannotCreateMockException: Cannot create mock for class java.util.Random. Mocking of non-interface types requires a code generation library. Please put an up-to-date version of byte-buddy or cglib-nodep on the class path.

此错误在 Spock documentation 中提到,它是由于 cglib 或 byte-buddy 在运行时不可用造成的。

考虑到 spock-core's pom lists both byte-buddy and cglib as compile dependencies,为什么它们不在运行时保留?换句话说,为什么我们需要将以下运行时依赖显式添加到我们的 build.gradle 文件中?

testRuntime "net.bytebuddy:byte-buddy:1.9.3" 

因为 (byte-buddycglib-nodep) 都标记为 <optional>true</optional>,其中从 Gradle 的角度来看,它们是 compileOnly 依赖项 - 参见:https://blog.gradle.org/introducing-compile-only-dependencies

Compile-only dependencies are distinctly different than regular compile dependencies. They are not included on the runtime classpath and they are non-transitive, meaning they are not included in dependent projects.

它们是可选的依赖项,因此如果您需要该功能,则需要包含它们

https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html