首页 > 解决方案 > 使用 Maven 在 Eclipse 中为 JUnit 5 配置类路径

问题描述

仅当 JUnit 5 引擎出现在项目的类路径中时,Eclipse (2018-09) 才支持 JUnit 5 测试。

现在我的 Maven 项目有两种可能性:

  1. 通过 Eclipse JUnit 库将其添加到项目中

    JUnitLib

    并仅将 API 添加到依赖项

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <scope>test</scope>
    </dependency>
    
  2. 将引擎和 API 添加到我的 Maven pom

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

如果我做前者,那么每个使用 Eclipse 的人都必须自己做。

如果我稍后再做,那么我的(测试)编译时类路径会被实现类污染,我(和其他 IDE 的用户)可能会使用它来代替 API 类。此外,这可能会导致与可能需要不同版本引擎的 IDE 发生冲突,而不是 cp 上的版本。IIRC 这就是 API 和引擎首先被拆分的全部原因。

不幸的是,Maven 中没有testRuntimeOnly范围(就像 gradle 中一样)。

TLDR:哪种方式是为 Maven 项目配置 JUnit 5 的正确方法?

标签: javaeclipsemavenjunit5

解决方案


如果我做前者,那么每个使用 Eclipse 的人都必须自己做。

我假设您打算让 Eclipse 用户有机会通过右键单击 JUnit 测试类并选择Run as > JUnit Test来执行测试。我不知道这是否正确,但要这样做,除了JUnit Jupiter API/Engine之外,您还需要添加一个额外的依赖项,即JUnit Platform Launcher

例如:

<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-api</artifactId>
  <version>5.4.2</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <version>5.4.2</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.platform</groupId>
  <artifactId>junit-platform-launcher</artifactId>
  <version>1.4.2</version>
  <scope>test</scope>
</dependency>

不确定它是否相关,但我使用的是maven-surefire-plugin版本 2.22.1,如果缺少JUnit Platform Launcher ,则会引发ClassNotFoundException


推荐阅读