Fix dynamic agent loading warning in Gradle

Clayton Walker - Jan 13 '24 - - Dev Community

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
Enter fullscreen mode Exit fullscreen mode

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 {
    val testAgentFiles = testAgent.incoming.files
    jvmArgumentProviders.add {
        testAgentFiles.map { "-javaagent:${it.absolutePath}" }
    }
}

// if using test suites
testing.suites {
    val test by existing(JvmTestSuite::class) {
        targets.configureEach {
            testTask.configure {
                val testAgentFiles = testAgent.incoming.files
                jvmArgumentProviders.add {
                    testAgentFiles.map { "-javaagent:${it.absolutePath}" }
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Follow the upstream issue for updates.

EDIT 3/2/2025:
Added test.task option
Replaced direct jvmArgs with jvmArgumentProviders to avoid configuration errors on older versions of Gradle 8

. . . . . .