How to automatically migrate from JUnit 4 to JUnit 5?

本秂侑毒 提交于 2019-12-02 00:06:05

The tooling at the moment is not great, but improving:

  • IntelliJ: Migrates most annotations to JUnit 5 versions. Hovewer, does not do anything if your test file contains @Rules (e.g., ExpectedException) as of v2018.2.
  • Error Prone: contains built-in refactorings to automatically migrate various JUnit 4 exception-testing idioms (try/fail/catch/assert, ExpectedExceptions, @Test(expected = …)) to assertThrows, perfectly augmenting IntelliJ.

I recommend the following steps:

  1. Add JUnit 5 artefacts to your test dependencies.
  2. Install Error Prone compiler.
  3. Configure it to produce a patch to migrate to assertThrows, enabling the following checks (the example Maven configuration is below):
    • TryFailRefactoring,
    • ExpectedExceptionRefactoring,
    • TestExceptionRefactoring.
  4. Use IntelliJ built-in refactorings to migrate JUnit 4 annotations and methods to JUnit 5 counterparts.

I am not aware of any tools that help to automatically migrate Parameterized tests, or rules other than ExpectedException.

Here is an example Error Prone configuration:

<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!