In the spirit of this question from JUnit 3 to JUnit 4, are there any list of regular expressions to efficiently migrate from the junit 4 API to the junit 5 API, regardless of the code size?
Asked
Active
Viewed 1,994 times
6
-
you can't migrate custom rules anyway.. – Izbassar Tolegen Oct 01 '17 at 16:42
-
1See https://stackoverflow.com/q/46882930/1072626, specifically [this answer](https://stackoverflow.com/a/47055280/1072626). – vossad01 Jun 04 '18 at 19:12
2 Answers
8
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
@Rule
s (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,
ExpectedException
s,@Test(expected = …)
) toassertThrows
, perfectly augmenting IntelliJ.
I recommend the following steps:
- Add JUnit 5 artefacts to your test dependencies.
- Install Error Prone compiler.
- Configure it to produce a patch to migrate to
assertThrows
, enabling the following checks (the example Maven configuration is below):- TryFailRefactoring,
- ExpectedExceptionRefactoring,
- TestExceptionRefactoring.
- 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>

Dmitry Timofeev
- 329
- 2
- 10
2
With openrewrite you can migrate automagically.
Just run:
mvn org.openrewrite.maven:rewrite-maven-plugin:4.36.0:run -Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-testing-frameworks:1.28.0 -Drewrite.activeRecipes=org.openrewrite.java.testing.junit5.JUnit5BestPractices

Geoffrey De Smet
- 26,223
- 11
- 73
- 120