Migrate JUnit 4 to JUnit 5 automatically
The Symflower tool allows to migrate code, packages, dependencies and whole projects automatically, with no manual changes required. This page showcases scenarios on how to migrate JUnit 4 to JUnit 5.
You can find a general introduction to symflower migrate
and all available migrations in the command-specific documentation.
Migrate a single file using the CLI
This scenario showcases how to use the Symflower CLI to migrate a single file from JUnit 4 to JUnit 5.
As a running example we use the google/gson
project:
# Clone the repository.
git clone https://github.com/google/gson
# Change the working directory to the cloned repository to apply commands with the correct context.
cd gson/gson
We are migrating the src/test/java/com/google/gson/CommentsTest.java
file, which looks like this:
package com.google.gson;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import org.junit.Test;
/**
* Tests that by default Gson accepts several forms of comments.
*
* @author Jesse Wilson
*/
public final class CommentsTest {
/** Test for issue 212. */
@Test
public void testParseComments() {
String json =
"[\n"
+ " // this is a comment\n"
+ " \"a\",\n"
+ " /* this is another comment */\n"
+ " \"b\",\n"
+ " # this is yet another comment\n"
+ " \"c\"\n"
+ "]";
List<String> abc = new Gson().fromJson(json, new TypeToken<List<String>>() {}.getType());
assertThat(abc).containsExactly("a", "b", "c").inOrder();
}
}
Run the command to migrate the file:
symflower migrate --type=junit4-to-junit5 src/test/java/com/google/gson/CommentsTest.java
Running the command changes the import org.junit.Test
to org.junit.jupiter.api.Test
which is everything that needs to change for this file. (However, to execute the test file, the project configuration needs to be changed.)
package com.google.gson;
import static com.google.common.truth.Truth.assertThat;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* Tests that by default Gson accepts several forms of comments.
*
* @author Jesse Wilson
*/
public final class CommentsTest {
/** Test for issue 212. */
@Test
public void testParseComments() {
String json =
"[\n"
+ " // this is a comment\n"
+ " \"a\",\n"
+ " /* this is another comment */\n"
+ " \"b\",\n"
+ " # this is yet another comment\n"
+ " \"c\"\n"
+ "]";
List<String> abc = new Gson().fromJson(json, new TypeToken<List<String>>() {}.getType());
assertThat(abc).containsExactly("a", "b", "c").inOrder();
}
}
Since we only migrated a single file, we still need to update the dependencies to JUnit 5 in the build file. You can find a detailed guide at How to migrate from JUnit 4 to JUnit 5: a step-by-step guide.
Afterwards you can run the test of the migrated file:
mvn test -Dtest=com.google.gson.CommentsTest