# Replace JUnit 4 Annotations with JUnit Jupiter
# Description
In JUnit Jupiter, annotations reside in org.junit.jupiter.api
(opens new window), while in JUnit 4 annotations reside in org.junit
(opens new window).
This rule, replaces the following JUnit 4 annotations:
- @Test (opens new window)
- @Ignore (opens new window)
- @Before (opens new window)
- @BeforeClass (opens new window)
- @After (opens new window)
- @AfterClass (opens new window)
respectively with the JUnit Jupiter API (opens new window) alternatives:
- @Test (opens new window)
- @Disable (opens new window)
- @BeforeEach (opens new window)
- @BeforeAll (opens new window)
- @AfterEach (opens new window)
- @AfterAll (opens new window)
By replacing each of these JUnit 4 annotations by the corresponding Jupiter alternatives, this rule promotes a stepwise transition to JUnit Jupiter.
Requirements
This rule requires the following library to be present:
- junit:junit:4.13
- org.junit.jupiter:junit-jupiter-api:5.0.0
# Benefits
Migrates JUnit 4 tests to JUnit 5.
# Tags
# Code Changes
# Replacing Imports and Annotations
Pre
package test.examples;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class ExampleTest {
@Before
public void beforeTestMethod() {
// ..
}
@After
public void afterTestMethod() {
// ..
}
@BeforeClass
public void beforeTestClass() {
// ..
}
@AfterClass
public void afterTestClass() {
// ..
}
@Ignore
@Test
public void test() {
// ..
}
}
Post
package test.examples;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class ExampleTest {
@BeforeEach
public void beforeTestMethod() {
// ..
}
@AfterEach
public void afterTestMethod() {
// ..
}
@BeforeAll
public void beforeTestClass() {
// ..
}
@AfterAll
public void afterTestClass() {
// ..
}
@Disabled
@Test
public void test() {
// ..
}
}
# Limitations
The transformation cannot be performed automatically if:
- Any of the
@Test
annotations contains properties, e.g.,@Test(timeout=...)
or@Test(expected=...)
. - Any other JUnit 4 annotation, which is not mentioned above, is used explicitly or implicitly in the test class.
You Want To Have Those Changes Done Automatically?
The automatic application of this rule is supported in the following jSparrow version:
# Properties
Property | Value |
---|---|
Rule ID | ReplaceJUnit4AnnotationsWithJupiter |
First seen in jSparrow version | 3.27.0 |
Minimum Java version | 8 |
Remediation cost | 15 min |