在 gradle 中隐藏传递依赖

Csu*_*uki 6 java gradle

项目设置:Gradle5、Spring5

我们想使用JUnit5作为我们的测试工具。我们从Spring5依赖项中排除了JUnit4,但我们有一个仍然依赖于JUnit4 的第 3 方库,并且不允许排除它。我们尝试全局排除JUnit4,但我们的项目无法编译。

目标:我们的目标是隐藏JUnit4的编译依赖项,以便开发人员不会意外使用JUnit4类而不是JUnit5类。

摇篮:

dependencies {
    implementation('org.springframework.boot:spring-boot-starter')
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'junit', module: 'junit'
    }
    testImplementation('org.testcontainers:testcontainers:1.10.2') {
        exclude group: 'junit', module: 'junit'
    }
    testImplementation('org.testcontainers:postgresql:1.7.3') {
        exclude group: 'junit', module: 'junit'
    }
    testImplementation('org.testcontainers:junit-jupiter:1.11.2')
    testImplementation('org.mockito:mockito-junit-jupiter:2.23.0')
    testImplementation('org.junit.jupiter:junit-jupiter-api:5.3.1')
    testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.3.1')
}

Run Code Online (Sandbox Code Playgroud)

我们的依赖项中的相关部分:

testCompileClasspath
+--- org.springframework.boot:spring-boot-starter-test -> 2.1.3.RELEASE
    ... (junit4 excluded)
+--- org.testcontainers:testcontainers:1.10.2
|    +--- junit:junit:4.12
|    |    \--- org.hamcrest:hamcrest-core:1.3
     ...
+--- org.junit.jupiter:junit-jupiter-api:5.3.1 (*)
\--- org.junit.jupiter:junit-jupiter-engine:5.3.1
Run Code Online (Sandbox Code Playgroud)

期望的行为:

dependencies {
    implementation('org.springframework.boot:spring-boot-starter')
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'junit', module: 'junit'
    }
    testImplementation('org.testcontainers:testcontainers:1.10.2') {
        exclude group: 'junit', module: 'junit'
    }
    testImplementation('org.testcontainers:postgresql:1.7.3') {
        exclude group: 'junit', module: 'junit'
    }
    testImplementation('org.testcontainers:junit-jupiter:1.11.2')
    testImplementation('org.mockito:mockito-junit-jupiter:2.23.0')
    testImplementation('org.junit.jupiter:junit-jupiter-api:5.3.1')
    testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.3.1')
}

Run Code Online (Sandbox Code Playgroud)

您可以在github上找到示例代码

Lou*_*met 4

如果您希望库在编译时不可用但在运行时仍然存在,您可以简单地执行以下操作:

configurations {
    testImplementation {
        // Globally exclude JUnit, will not be on the testCompileClasspath thus
        exclude group: 'junit', module: 'junit'
    }
}
dependencies {
    // Make sure JUnit is on the testRuntimeClasspath
    testRuntimeOnly("junit:junit:4.12")
}
Run Code Online (Sandbox Code Playgroud)

如果您需要对另一个库的生产源进行类似的设置,请删除test配置名称的前缀并调整排除和依赖项坐标。