Skip to content

Commit 527467d

Browse files
authored
KAFKA-18356: Explicitly set up instrumentation for inline mocking (Java 21+) (#18339)
Reviewers: Mickael Maison <[email protected]>, Ismael Juma <[email protected]>
1 parent 9e9d2a2 commit 527467d

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

build.gradle

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ ext {
157157
libs.log4j2Api,
158158
libs.log4j2Core
159159
]
160-
160+
161161
}
162162

163163
allprojects {
@@ -484,11 +484,36 @@ subprojects {
484484
}
485485
}
486486

487+
// Workaround for Mockito Java Agent restrictions in Java 21+
488+
// Starting with Java 21, the JDK restricts libraries from attaching a Java agent
489+
// to their own JVM. As a result, Mockito’s inline mock maker (mockito-core)
490+
// fails without explicit instrumentation, and the JVM consistently emits warnings.
491+
// See also: https://javadoc.io/doc/org.mockito/mockito-core/latest/org.mockito/org/mockito/Mockito.html#mockito-instrumentation
492+
afterEvaluate { subproject ->
493+
def hasMockitoCore = subproject.configurations.findAll {
494+
it.canBeResolved
495+
}.any { config ->
496+
config.incoming.dependencies.any { dependency ->
497+
"$dependency" == libs.mockitoCore
498+
}
499+
}
500+
501+
if (hasMockitoCore) {
502+
subproject.configurations {
503+
mockitoAgent {
504+
transitive = false
505+
}
506+
}
507+
subproject.dependencies {
508+
mockitoAgent libs.mockitoCore
509+
}
510+
}
511+
}
512+
487513
// The suites are for running sets of tests in IDEs.
488514
// Gradle will run each test class, so we exclude the suites to avoid redundantly running the tests twice.
489515
def testsToExclude = ['**/*Suite.class']
490516

491-
492517
// This task will copy JUnit XML files out of the sub-project's build directory and into
493518
// a top-level build/junit-xml directory. This is necessary to avoid reporting on tests which
494519
// were not run, but instead were restored via FROM-CACHE. See KAFKA-17479 for more details.
@@ -518,6 +543,14 @@ subprojects {
518543
}
519544

520545
test {
546+
547+
doFirst {
548+
def mockitoAgentConfig = configurations.findByName('mockitoAgent')
549+
if (mockitoAgentConfig) {
550+
jvmArgs("-javaagent:${mockitoAgentConfig.asPath}")
551+
}
552+
}
553+
521554
maxParallelForks = maxTestForks
522555
ignoreFailures = userIgnoreFailures
523556

@@ -551,7 +584,7 @@ subprojects {
551584
maxFailures = userMaxTestRetryFailures
552585
}
553586
}
554-
587+
555588
finalizedBy("copyTestXml")
556589
}
557590

0 commit comments

Comments
 (0)