In newer versions java, dynamically loaded agents will be disallowed. Warnings like the following would be logged by your test runner.
WARNING: A Java agent has been loaded dynamically (/Users/cwalker/.gradle/caches/modules-2/files-2.1/net.bytebuddy/byte-buddy-agent/1.14.6/46e2545d7a97b6ccb195621650c5957279eb4812/byte-buddy-agent-1.14.6.jar)
WARNING: If a serviceability tool is in use, please run with -XX:+EnableDynamicAgentLoading to hide this warning
WARNING: If a serviceability tool is not in use, please run with -Djdk.instrument.traceUsage for more information
WARNING: Dynamic loading of agents will be disallowed by default in a future release
To fix this, we can get add a new agent configuration and map dependencies from that configuration to the -javaagent
flag.
Using the new test-suites plugin, that would look like the following.
val testAgent by configurations.creating
dependencies {
testAgent("net.bytebuddy:byte-buddy-agent:1.14.6")
}
// if configuring test task directly
tasks.test {
jvmArgumentProviders.add(
objects.newInstance<JavaAgentArgumentProvider>().apply {
classpath.from(testAgent)
}
)
}
// if using test suites
testing.suites {
val test by existing(JvmTestSuite::class) {
targets.configureEach {
testTask.configure {
jvmArgumentProviders.add(
objects.newInstance<JavaAgentArgumentProvider>().apply {
classpath.from(testAgent)
}
)
}
}
}
}
abstract class JavaAgentArgumentProvider : CommandLineArgumentProvider {
@get:Classpath
abstract val classpath: ConfigurableFileCollection
override fun asArguments() = classpath.files.map { "-javaagent:${it.absolutePath}" }
}
Follow the upstream issue for updates.
For simplicity, it may be easier to depend on a third-party dependency (such as javaagent-gradle-plugin) to handle agents.
EDIT 3/2/2025:
Added test.task option
Replaced direct jvmArgs with jvmArgumentProviders to avoid configuration errors on older versions of Gradle 8
EDIT 6/14/2025:
Added support for task relocatability by using a command-line configurator like in this comment https://github.com/mockito/mockito/issues/3037#issuecomment-2724136224 or this plugin https://github.com/bakdata/gradle-plugins/pull/63/files
Added link to ryandens' javaagent-gradle-plugin
Top comments (0)