
本文介绍如何将自定义源集(如 `testcommons`)的编译输出同时接入 `test` 和 `itest` 测试套件,实现测试工具类、辅助方法等代码的跨套件共享。
在 Gradle 8.2+ 的分层测试套件(Hierarchical Test Suites)模型下,每个测试套件(如 test、itest)拥有独立的依赖配置和类路径。若你已定义了 testcommons 源集用于存放通用测试工具类(例如断言封装、Mock 工具、TestContainers 配置等),需显式将其编译输出(即字节码)作为依赖添加到各测试套件中,否则这些类在运行时不可见。
关键在于:sourceSets["testcommons"].output 表示该源集的编译结果(classes + resources),可直接作为 implementation 依赖引入任意测试套件。但需注意声明顺序——sourceSets 块必须在 testing.suites 之前定义,否则 sourceSets["testcommons"] 将未初始化,导致构建失败。
以下是完整、可运行的 build.gradle 配置示例(Groovy DSL):
// ✅ 必须先定义 sourceSets,确保 testcommons 可被后续引用
sourceSets {
testcommons {
java {
srcDir 'src/testcommons/java'
}
resources {
srcDir 'src/testcommons/resources'
}
}
}
// ✅ 然后配置 testing 块,并为每个套件添加 testcommons 输出
testing {
suites {
test {
useJUnitJupiter()
dependencies {
implementation sourceSets["testcommons"].output
}
}
itest(JvmTestSuite) {
testType = TestSuiteType.INTEGRATION_TEST
dependencies {
implementation project()
implementation sourceSets["testcommons"].output // 同样引入!
}
configurations {
itestImplementation.extendsFrom testImplementation
itestRuntime.extendsFrom testRuntime
itestRuntimeOnly.extendsFrom testRuntimeOnly
}
}
}
}⚠️ 注意事项:不要使用 implementation project().sourceSets.testcommons.output —— 这是错误写法;应直接使用 sourceSets["testcommons"].output。若 testcommons 中依赖了其他库(如 org.junit.jupiter:junit-jupiter-api),需在 testcommons 的 dependencies 块中显式声明(它默认不继承 testImplementation):sourceSets { testcommons { // ... } } dependencies { testcommonsImplementation libs.junit.jupiter.api // 或 'org.junit.jupiter:junit-jupiter-api' }编译 testcommons 会自动触发(因被其他任务依赖),无需手动调用 ./gradlew testcommonsClasses。
最终效果:src/testcommons/java/com/example/TestUtils.java 中的公共工具类,既可在 src/test/java 的单元测试中使用,也可在 src/itest/java 的集成测试中无缝调用,真正实现测试资产复用,提升项目可维护性。










