JUnit 4 Migration

Understand the usage of JUnit 4 and Junit 5 runtimes.

Overview

As previously mentioned, JUnit Jupiter and JUnit Vintage both run on the same platform. JUnit Vintage can run JUnit 4 and JUnit 3 tests. JUnit Jupiter uses a different package name, so it doesn’t conflict with the existing JUnit 4. Tests written with the new JUnit Jupiter programming model and legacy JUnit 4 tests can coexist in the same project. If we have legacy projects with JUnit 4 tests and want to leverage the new programming model in JUnit Jupiter, we have three options when upgrading to JUnit 5:

  • We can keep the legacy JUnit 4 tests and runtime and use the JUnit 5 platform and Jupiter for new tests only.
  • We can use JUnit Vintage to run legacy JUnit 4 tests and use JUnit Jupiter to run new tests.
  • We can upgrade legacy JUnit 4 tests to use the JUnit Jupiter programming model and use JUnit Jupiter only.

We use a Spring Boot application created by Spring Initializer as the legacy application. We’ll see how to migrate this application using the three options above.

JUnit 4 and 5 runtimes

The legacy Spring Boot application already has JUnit 4 configured with a simple JUnit 4 test. We can keep the configuration and tests untouched and use JUnit Jupiter to write and execute new tests. We simply need to configure JUnit 5 to the application, following the instructions in Chapter 3 (Annotations, Tagging, and Filtering). For Gradle, after enabling the JUnit 5 plugin, the standard task test is disabled by default. To run JUnit 4 tests, we use the configuration in the code below to enable the task test. We can then use a Gradle test to run both JUnit 4 and 5 tests.

Get hands-on with 1400+ tech skills courses.