Verify basic test execution and annotation differences between JUnit 4 and JUnit 5
Preconditions (2)
✅ Expected Result: Both JUnit 4 and JUnit 5 tests run successfully and pass. Differences in annotations and features like @DisplayName are observed.
import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; @DisplayName("JUnit 5 Basic Test Class") public class JUnit5BasicTest { @BeforeEach void setup() { System.out.println("Setup before each test"); } @AfterEach void teardown() { System.out.println("Teardown after each test"); } @Test @DisplayName("Test addition: 2 + 2 = 4") void testAddition() { assertEquals(4, 2 + 2, "2 + 2 should equal 4"); } }
This test class uses JUnit 5 (Jupiter) annotations.
@BeforeEach runs before each test method to setup test conditions.
@AfterEach runs after each test method to cleanup.
@Test marks the test method.
@DisplayName provides a readable name for the test class and method.
assertEquals verifies the expected result.
This shows the key differences from JUnit 4, which uses @Before, @After, and lacks @DisplayName.
Now add parameterized tests in JUnit 5 to test addition with multiple input pairs
@Before from JUnit 4 in JUnit 5?@Before to run code before each test method.@Before with @BeforeEach to clarify it runs before each test method.import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CalculatorTest {
@Test
void addTest() {
int result = 2 + 3;
assertEquals(5, result);
}
}import org.junit.Before;
import org.junit.Test;
public class SampleTest {
@Before
public void setup() {
System.out.println("Setup");
}
@Test
void testMethod() {
System.out.println("Test");
}
}@Before with @BeforeEach and updating imports to Jupiter packages are required for migration.Pass the test and this pattern moves unknown