Sub topic 17
Coming from JUnit 4
Many Java projects started out with JUnit 4, the version of JUnit that came before JUnit 5. You may join a team whose old tests still use it, or you may find JUnit 4 examples online. This chapter shows how the two versions differ and how to move old tests to JUnit 5 one step at a time.
You already know the JUnit 5 features from earlier chapters. Here you will learn to recognize their JUnit 4 versions and translate them.
Why the Two Versions Look Different
JUnit 5 is not a small update. Its authors rebuilt it from scratch. It has three parts:
- The JUnit Platform is the base layer. It finds tests and runs them. IDEs and build tools such as Maven and Gradle talk to the Platform.
- JUnit Jupiter is the new way to write tests: the
@Test,@BeforeEach, andassertThrowsyou have been using. It also includes a test engine, which is a plug-in that knows how to run one style of test. - JUnit Vintage is a test engine that runs old JUnit 3 and JUnit 4 tests on the new Platform.
The Vintage engine matters most during a migration. A migration is the work of moving code from an old tool to a new one. With Vintage, old and new tests can run side by side in the same build, so you do not have to convert everything at once.
The Package Name Changed
The first difference you will notice is in the import lines. JUnit 4 classes live in the org.junit package. JUnit 5 classes live in org.junit.jupiter.api.
| Kind of class | JUnit 4 import | JUnit 5 import |
|---|---|---|
| Test annotation | `org.junit.Test` | `org.junit.jupiter.api.Test` |
| Assertions | `org.junit.Assert` | `org.junit.jupiter.api.Assertions` |
| Assumptions | `org.junit.Assume` | `org.junit.jupiter.api.Assumptions` |
Annotation Changes
Most JUnit 4 annotations have a JUnit 5 version with a clearer name.
| JUnit 4 | JUnit 5 | What it does |
|---|---|---|
| `@Before` | `@BeforeEach` | Runs before every test |
| `@After` | `@AfterEach` | Runs after every test |
| `@BeforeClass` | `@BeforeAll` | Runs once before all tests in the class |
| `@AfterClass` | `@AfterAll` | Runs once after all tests in the class |
| `@Ignore` | `@Disabled` | Skips a test |
| `@Category` | `@Tag` | Labels tests so you can filter them |
| `@RunWith` | `@ExtendWith` | Adds extra behavior to a test class |
| `@Rule`, `@ClassRule` | `@ExtendWith` and built-in features such as `@TempDir` | Shares reusable test setup |
| `@Test(expected = ...)` | `assertThrows(...)` | Checks for an exception |
| `@Test(timeout = ...)` | `@Timeout` or `assertTimeout(...)` | Sets a time limit |
The new names say when each method runs. @BeforeEach plainly means "before each test." The old @Before did not say that.
Smaller Rules That Changed
Some changes are easy to miss.
- Visibility. Visibility tells Java who may use a class or method. JUnit 4 required test classes and methods to be
public. JUnit 5 does not. Package-private (no keyword) is the usual style. - Message position. In JUnit 4 the optional failure message came first:
assertEquals("message", expected, actual). In JUnit 5 it comes last:assertEquals(expected, actual, "message"). If you only change the import, a JUnit 4 call with a message may still compile, but the values end up in the wrong parameters. - assertThat is gone. JUnit 4 had
Assert.assertThatfor Hamcrest matchers. Hamcrest is a separate library of readable checks. JUnit 5 dropped this method. If you still want it, importorg.hamcrest.MatcherAssert.assertThatfrom Hamcrest itself. - Static
@BeforeAll. Like@BeforeClass, a@BeforeAllmethod must bestaticby default.
A Worked Example
Here is a JUnit 4 test for the Calculator class from earlier chapters. It uses @Before, a message-first assertion, and @Test(expected = ...).
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class CalculatorJUnit4Test {
private Calculator calculator;
@Before
public void setUp() {
calculator = new Calculator();
}
@Test
public void addReturnsSum() {
assertEquals("2 + 3 should be 5", 5, calculator.add(2, 3));
}
@Test(expected = IllegalArgumentException.class)
public void divideByZeroThrows() {
calculator.divide(10, 0);
}
}Here is the same test in JUnit 5.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class CalculatorJUnit5Test {
private Calculator calculator;
@BeforeEach
void setUp() {
calculator = new Calculator();
}
@Test
void addReturnsSum() {
assertEquals(5, calculator.add(2, 3), "2 + 3 should be 5");
}
@Test
void divideByZeroThrows() {
IllegalArgumentException ex = assertThrows(
IllegalArgumentException.class,
() -> calculator.divide(10, 0));
assertEquals("divisor must not be zero", ex.getMessage());
}
}Look at what changed:
- The imports now come from
org.junit.jupiter.api. @Beforebecame@BeforeEach.- The
publickeywords are gone. - The message moved to the end of
assertEquals. @Test(expected = ...)becameassertThrows.
The last change makes the test stronger. With expected, the test passes if any line in the method throws that exception, even a setup line. With assertThrows, only the lambda (the () -> ... code) has to throw. You also get the exception back, so you can check its message.
Running Old and New Tests Together
To keep JUnit 4 tests running while you convert them, add the Vintage engine next to Jupiter. In Maven:
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.11.3</version>
<scope>test</scope>
</dependency>
</dependencies>In Gradle with the Kotlin DSL:
dependencies {
testImplementation(platform("org.junit:junit-bom:5.11.3"))
testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation("junit:junit:4.13.2")
testRuntimeOnly("org.junit.vintage:junit-vintage-engine")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test {
useJUnitPlatform()
}The Maven Vintage engine brings in JUnit 4 (junit:junit) for you. In Gradle, testRuntimeOnly dependencies are not visible when tests compile, so the Gradle example adds junit:junit with testImplementation. Without that line, your JUnit 4 test classes would not compile.
Replacing Runners and Rules
JUnit 4 had two ways to add behavior: runners (@RunWith) and rules (@Rule). A class could use only one runner, which was a common problem. JUnit 5 replaces both with extensions, and a class can use many of them.
Common replacements:
@RunWith(MockitoJUnitRunner.class)becomes@ExtendWith(MockitoExtension.class). You need themockito-junit-jupiterdependency.@Rule TemporaryFolderbecomes a@TempDirfield or parameter.@Rule ExpectedExceptionbecomesassertThrows.@RunWith(Parameterized.class)becomes@ParameterizedTestwith a source such as@CsvSource.
A Safe Migration Plan
- Add Jupiter and Vintage to the build. Run all tests and confirm they still pass.
- Pick one test class. Change its imports and annotations.
- Move messages to the last position and replace
expectedwithassertThrows. - Replace runners and rules with extensions or built-in features.
- Run the tests again. Make sure the number of tests run did not drop.
- Repeat for each class, then remove Vintage.
Step 5 catches the silent-skip problem from the warning above. If a class had five tests before and the report shows zero after, an import is wrong.
Exercise
A JUnit 4 test has @BeforeClass public static void init(), @Ignore @Test public void slowTest(), and assertTrue("list should be empty", list.isEmpty()). Write the JUnit 5 versions of these three pieces.
Show answer
@BeforeAll static void init() (the method still has to be static); @Disabled @Test void slowTest(); and assertTrue(list.isEmpty(), "list should be empty"), with the message moved to the last position. The imports come from org.junit.jupiter.api.
Exercise
After you convert a class, the build report shows that its tests did not run, and there are no errors. What is the most likely cause?
Show answer
The class still imports org.junit.Test (JUnit 4) instead of org.junit.jupiter.api.Test. The Jupiter engine ignores JUnit 4 annotations. If the Vintage engine is not on the classpath, nothing runs those tests and no error appears. Fix the import.
Exercise
Why is assertThrows a better check than @Test(expected = IllegalArgumentException.class)?
Show answer
expected passes if any line in the test throws the exception, including setup code that throws it by accident. assertThrows checks only the code inside the lambda. It also returns the exception, so you can check its message.