Gradle 8.8+Jacoco 0.8.11在Java17环境下测试执行失败求助
问题描述
Spring Boot项目使用Gradle 8.8、Jacoco 0.8.11、Java 17,运行测试时无法正常执行,核心异常为无法插装java.util.UUID类,找不到$jacocoAccess字段。
Gradle配置
jacoco { toolVersion = "0.8.11" } java { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } test { systemProperty "Log4jContextSelector", "org.apache.logging.log4j.core.selector.BasicContextSelector" jacoco { destinationFile = file("$buildDir/jacoco/jacocoTest.exec") classDumpDir = file("$buildDir/jacoco/classpathdumps") } } jacocoTestReport { reports { html.required.set(true) } afterEvaluate { classDirectories.setFrom(files(classDirectories.files.collect { fileTree(dir: it, exclude: [ '**/config/*', '**/models/*', '**/*Application*' ]) })) } }
异常栈信息
Exception in thread "main" java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:491) at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:503) Caused by: java.lang.RuntimeException: Class java/util/UUID could not be instrumented. at org.jacoco.agent.rt.internal_e5875b2.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:140) at org.jacoco.agent.rt.internal_e5875b2.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:101) at org.jacoco.agent.rt.internal_e5875b2.PreMain.createRuntime(PreMain.java:55) at org.jacoco.agent.rt.internal_e5875b2.PreMain.premain(PreMain.java:47) ... 6 more Caused by: java.lang.NoSuchFieldException: $jacocoAccess at java.base/java.lang.Class.getField(Class.java:2117) at org.jacoco.agent.rt.internal_e5875b2.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:138) ... 9 more *** java.lang.instrument ASSERTION FAILED ***:
解决方案
1. 升级Jacoco版本
Jacoco 0.8.11对Java 17的字节码插装支持存在缺陷,升级到0.8.12及以上版本(推荐0.8.13)可解决该问题。修改Gradle配置中的Jacoco版本:
jacoco { toolVersion = "0.8.13" }
2. 排除JDK系统类插装(临时方案)
若暂时无法升级Jacoco,可通过配置Jacoco代理参数,排除对JDK系统类的插装。调整test任务配置:
test { systemProperty "Log4jContextSelector", "org.apache.logging.log4j.core.selector.BasicContextSelector" // 配置Jacoco代理,排除java包下的所有类 jvmArgs = [ "-javaagent:${jacocoAgentJar}=destfile=${buildDir}/jacoco/jacocoTest.exec,excludes=java/**" ] // 注释原jacoco块,避免重复配置代理 // jacoco { // destinationFile = file("$buildDir/jacoco/jacocoTest.exec") // classDumpDir = file("$buildDir/jacoco/classpathdumps") // } }
3. 验证Gradle与Jacoco兼容性
Gradle 8.8官方推荐搭配Jacoco 0.8.12及以上版本使用,确保版本匹配可避免兼容性问题。
内容的提问来源于stack exchange,提问作者rakeeee
相关产品推荐
相关产品推荐

