junit-bom 和 junit platform 的用途是什么?我应该将它们包含在 gradle 依赖项中吗?

she*_*hen 19 java junit gradle junit5 junit-jupiter

我正在阅读Junit 5 用户指南。它引导我找到JUnit 5 Jupiter Gradle Sample,这是将 Junit 5 与 Gradle 结合使用的最简单示例。在build.gradle文件中,有 2 个依赖项,junit-jupiter并且junit-bom. 而在testtask中,它也调用了useJUnitPlatform()function。

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(platform('org.junit:junit-bom:5.7.1'))
    testImplementation('org.junit.jupiter:junit-jupiter')
}

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,这junit-jupiter是聚合工件,它提取以下 3 个工件,

  1. junit-jupiter-api(编译依赖)
  2. junit-jupiter-engine(运行时依赖)
  3. junit-jupiter-params(用于参数化测试)

所以我想junit-jupiter在我的项目中运行 JUnit Jupiter 已经足够了(如果我错了,请纠正我)。我想知道这里是什么junit-bom以及JUnitPlatform有什么用?我可以简单地摆脱它们吗?感谢大家:)

rie*_*pil 21

junit-bom是 JUnit 的物料清单 (BOM)。包含此 BOM 时,它将确保为您调整和管理所有 JUnit 5 依赖项版本。您可以在本文中找到有关 BOM 概念的更多信息。

这就是为什么您在导入时不必指定版本junit-jupiter

// with the BOM, no version needed
testImplementation('org.junit.jupiter:junit-jupiter')

// when using no BOM, version info is needed
testImplementation('org.junit.jupiter:junit-jupiter:5.7.1')
Run Code Online (Sandbox Code Playgroud)

如果您从同一项目导入多个依赖项,您将看到 BOM 的优势。当只使用一个依赖项时,它可能看起来是多余的:

// only define the version at a central place, that's nice
testImplementation(platform('org.junit:junit-bom:5.7.1'))
testImplementation('org.junit.jupiter:junit-jupiter')
testImplementation('org.junit.vintage:junit-vintage-engine') // when you want to also run JUnit 3 + 4 tests
Run Code Online (Sandbox Code Playgroud)

指示useJUnitPlatform()Gradle 测试任务使用 JUnit 平台来执行测试。这是必需的。

就您而言,您有一个最小的工作设置来将 JUnit 5 用于 Gradle 项目。您可以做的是自行删除junit-bom并添加版本信息:

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.7.1')
}

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}
Run Code Online (Sandbox Code Playgroud)

但我会坚持 JUnit 团队的推荐以及他们在 GitHub 上的示例项目。