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

Geo*_*met 3 junit junit4 junit5

从JUnit 3到JUnit 4这个问题的精神,是否有任何正则表达式列表可以有效地从junit 4 API迁移到junit 5 API,无论代码大小如何?

Dmi*_*eev 6

目前的工具并不是很好,但改进了:

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

我建议采取以下步骤:

  1. 将JUnit 5工件添加到测试依赖项中.
  2. 安装 Error Prone编译器.
  3. 配置它以生成要迁移到的修补程序assertThrows,启用以下检查(示例Maven配置如下):
    • TryFailRefactoring,
    • ExpectedExceptionRefactoring,
    • TestExceptionRefactoring.
  4. 使用IntelliJ内置重构将JUnit 4注释和方法迁移到JUnit 5对应项.

我不知道有任何工具可以帮助自动迁移Parameterized测试或其他规则ExpectedException.

以下是Error Prone配置示例:

<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>
Run Code Online (Sandbox Code Playgroud)