声明 JUnit 5 依赖项的正确方法

问题描述 投票:0回答:1

有些人会告诉你只需声明:

    <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>

但是,如果您像这样设置项目,

maven-dependency-plugin
将会失败,因为依赖项是错误的:

[INFO] --- dependency:3.8.1:analyze-only (analyze-only) @ function ---
[ERROR] Used undeclared dependencies found:
[ERROR]    org.junit.jupiter:junit-jupiter-api:jar:5.11.3:test
[ERROR] Unused declared dependencies found:
[ERROR]    org.junit.jupiter:junit-jupiter:jar:5.11.3:test

如果你只是将

junit-jupiter
换成
junit-jupiter-api
,当尝试使用 maven 运行 junit5 测试时,你会遇到类似 java.lang.NoClassDefFoundError: org/junit/platform/commons/PreconditionViolationException 的问题

你可以尝试:

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-commons</artifactId>
            <scope>test</scope>
        </dependency>

但是您仍然需要手动将第二个依赖项标记为已使用:

                            <usedDependencies>
                                <usedDependency>org.junit.platform:junit-platform-commons</usedDependency>
                            </usedDependencies>

这有点尴尬。 有没有更好的方法来处理这个问题?

我认为这里的根本问题是

junit-jupiter
工件是一个“聚合器”依赖项,这与
maven-dependency-plugin
期望声明 Maven 依赖项的方式不兼容。

FTR 这是 JUnit 5 模块结构的新功能,JUnit 4 不存在此类问题。

maven junit5 dependency-management
1个回答
0
投票

你不应该担心这个。正确的方法是使用 Maven 注册表的 JUnit 页面上提供的内容。

即使使用 Spring Boot 的 POM 文件,Maven 也会发现同样的问题。这是我的 Spring Boor 项目之一的输出:

[WARNING] Used undeclared dependencies found:
[WARNING]    org.junit.jupiter:junit-jupiter-api:jar:5.11.3:test
[WARNING]    org.mockito:mockito-core:jar:5.14.2:test
[WARNING]    org.apache.commons:commons-lang3:jar:3.17.0:compile
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.