如何自动从 JUnit 4 迁移到 JUnit 5?

How to automatically migrate from JUnit 4 to JUnit 5?

本着this question from JUnit 3 to JUnit 4的精神,是否有任何正则表达式列表可以有效地从 junit 4 API 迁移到 junit 5 API,不考虑代码大小?

目前的工具不是很好,但正在改进:

  • IntelliJ:将大多数注释迁移到 JUnit 5 版本。但是,如果您的测试文件包含自 v2018.2 起的 @Rules(例如 ExpectedException),则不会执行任何操作。
  • Error Prone:包含内置重构,可自动将各种 JUnit 4 异常测试习语(try/fail/catch/assert、ExpectedExceptions、@Test(expected = …))迁移到 assertThrows,完美增强 IntelliJ。

我推荐以下步骤:

  1. 将 JUnit 5 工件添加到您的测试依赖项中。
  2. Install 容易出错的编译器。
  3. Configure 它生成一个补丁以迁移到 assertThrows,启用以下检查(示例 Maven 配置如下):
    • TryFail重构,
    • 预期异常重构,
    • 测试异常重构。
  4. 使用内置的 IntelliJ refactorings 迁移 JUnit 4 JUnit 5 对应的注释和方法。

我不知道有任何工具可以帮助自动迁移 Parameterized 测试,或者 ExpectedException 以外的规则。

这是一个容易出错的配置示例:

<build>
  <plugins>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.0</version>
      <configuration>
        <compilerId>javac-with-errorprone</compilerId>
        <showWarnings>true</showWarnings>
        <forceJavacCompilerUse>true</forceJavacCompilerUse>
        <source>${java.compiler.source}</source>
        <target>${java.compiler.target}</target>
        <compilerArgs>        
          <arg>-XepPatchChecks:TryFailRefactoring,ExpectedExceptionRefactoring,TestExceptionRefactoring</arg>
          <arg>-XepPatchLocation:${project.basedir}</arg>
        </compilerArgs>
      </configuration>
      <dependencies>
        <dependency>
          <groupId>org.codehaus.plexus</groupId>
          <artifactId>plexus-compiler-javac-errorprone</artifactId>
          <version>2.8.3</version>
        </dependency>
        <dependency>
          <groupId>com.google.errorprone</groupId>
          <artifactId>error_prone_core</artifactId>
          <version>2.3.2</version>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
</build>