【问题标题】:How to make Maven play nice with JUnit?如何让 Maven 与 JUnit 配合得很好?
【发布时间】:2019-05-18 02:37:46
【问题描述】:

Maven surefire 插件只运行以单词test 开头或结尾的测试。这在 JUnit 中处理起来确实很麻烦,原因有两个:

1 - 我已经必须将@Test 添加到我的所有测试方法中,因此还必须附加单词test 是重复的。

2 - 在 JUnit 中,如果我想禁用某些测试,我只需用@Disabled 标记它,所以如果我使用的是surefire,我还必须重命名测试方法。

有什么方法可以让surefire 与JUnit 配合得很好?这样,只运行标有@Test 的内容并自动忽略@Disabled 方法?


目前我的pom.xml是这样的(只包括测试相关的项目以节省空间):

<packaging>jar</packaging>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

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

<build>
    <pluginManagement>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.1</version>
        </plugin>
    </pluginManagement>
</build>

【问题讨论】:

  • 你的假设是完全错误的。 Surefire 插件与您正在使用的单元测试框架有关...您使用的是 JUnit 4 吗?你的 pom 文件是什么样子的?
  • 我在 IntelliJ IDEA 中使用 JUnit 5,JUnit 有 scope 的测试。除了我测试了所有这些,我在网上看到这是预期的行为,这不是假设,我是在测试和研究后发布的
  • By default, the Surefire Plugin will automatically include all test classes with the following wildcard patterns: "**/Test*.java"....maven.apache.org/surefire/maven-surefire-plugin/examples/…
  • 有两件事。您引用的是方法名称而不是帖子中的类……现在您引用的是命名约定?此外,我强烈建议阅读有关 JUnit5 支持 maven.apache.org/surefire/maven-surefire-plugin/examples/… 的文档,这表明您使用了错误的依赖项(您需要添加 junit-jupiter-engine 并且可能是补充 junit-jupiter-api)...但是引擎是最重要的...

标签: maven junit maven-3 maven-surefire-plugin junit5


【解决方案1】:

要使用 Maven 运行 JUnit Jupiter 测试,您必须使用 junit-jupiter-engine 而不是 junit-jupiter-api。

<dependencies>
    [...]
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.3.2</version>
        <scope>test</scope>
    </dependency>
    [...]
</dependencies>

您可以添加 junit-jupiter-api 作为补充工件。此外,您至少应该使用 maven-surefire-plugin 2.22.1+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-07
    • 2010-09-11
    • 1970-01-01
    • 2011-10-24
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    相关资源
    最近更新 更多