Gradle 集成测试套件取决于 testImplementation 依赖项

Gradle integration test suite depending on testImplementation dependencies

我正在尝试迁移到 Gradle 7.3 中引入的 test suites。我想做的是将 testImplementation 依赖项添加到我的集成测试中。

testing {
    suites { 
        val test by getting(JvmTestSuite::class) { 
            useJUnitJupiter() 
        }

        val integrationTest by registering(JvmTestSuite::class) { 
            dependencies {
                implementation(project) // This adds dependencies to the prod code
                // What to add to automatically use testImplementation deps?
            }
            ...
 
        }
    }
}

您可能想让 integrationTestImplementation 配置扩展 testImplementation 配置——就像 testImplementation 默认情况下已经扩展 implementation 一样。另请参阅 configuration inheritance.

上的文档

这是一个独立的例子(使用 Gradle 7.3.2 测试):

plugins {
    `java-library`
}

repositories {
    mavenCentral()
}

testing {
    suites { 
        val test by getting(JvmTestSuite::class) { 
            useJUnitJupiter() 
            dependencies {
                implementation("org.assertj:assertj-core:3.21.0")
            }
        }

        val integrationTest by registering(JvmTestSuite::class) { 
            dependencies {
                // TODO add any integration test only dependencies here
            }
        }
    }
}

// Here’s the bit that you’re after:
val integrationTestImplementation by configurations.getting {
    extendsFrom(configurations.testImplementation.get())
}

如果你运行./gradlew dependencies --configuration integrationTestRuntimeClasspath配置了配置继承,那么你将得到以下输出(缩写):

integrationTestRuntimeClasspath - Runtime classpath of source set 'integration test'.
+--- org.junit.jupiter:junit-jupiter:5.7.2
|    +--- org.junit:junit-bom:5.7.2
|    |    …
|    +--- org.junit.jupiter:junit-jupiter-api:5.7.2
|    |    …
|    +--- org.junit.jupiter:junit-jupiter-params:5.7.2
|    |    …
|    \--- org.junit.jupiter:junit-jupiter-engine:5.7.2
|         …
\--- org.assertj:assertj-core:3.21.0

但是,如果您 运行 相同的命令 没有 配置继承,那么您将得到以下输出(缩写)——注意缺少 org.assertj:assertj-core:3.21.0依赖:

integrationTestRuntimeClasspath - Runtime classpath of source set 'integration test'.
\--- org.junit.jupiter:junit-jupiter:5.7.2
     +--- org.junit:junit-bom:5.7.2
     |    …
     +--- org.junit.jupiter:junit-jupiter-api:5.7.2
     |    …
     +--- org.junit.jupiter:junit-jupiter-params:5.7.2
     |    …
     \--- org.junit.jupiter:junit-jupiter-engine:5.7.2

根据答案评论中的要求,这里还有一种方法可以使单元测试套件中的测试数据 class 可用于集成测试:

sourceSets.named("integrationTest") {
    java {
        val sharedTestData = project.objects.sourceDirectorySet("testData",
                "Shared test data")
        sharedTestData.srcDir("src/test/java")
        sharedTestData.include("com/example/MyData.java")
        source(sharedTestData)
    }
}