What are the differences between JUnit 4 and JUnit 5 versions in the context of testing?
sobes.tech AI
Answer from AI
Main differences between JUnit 4 and JUnit 5:
-
Architecture: JUnit 5 consists of several modules (JUnit Platform, JUnit Jupiter, JUnit Vintage), allowing to run tests of different versions and extend functionality. JUnit 4 is monolithic.
-
Annotations:
- New annotations appeared in JUnit 5:
@BeforeEachinstead of@Before,@AfterEachinstead of@After,@BeforeAllinstead of@BeforeClass,@AfterAllinstead of@AfterClass. @Testin JUnit 5 supports new features, such as specifying expected exceptions viaassertThrowsinstead of annotation parameters.
- New annotations appeared in JUnit 5:
-
Extensibility: JUnit 5 provides an extensible extension model (Extension API), replacing rules and runners from JUnit 4.
-
Support for lambda expressions and Java 8+: JUnit 5 leverages Java 8 features, simplifying test writing and improving readability.
-
Parameterized tests: JUnit 5 has improved support for parameterized tests with more flexible data sources.
Example of a simple test in JUnit 5:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void addition() {
assertEquals(2, 1 + 1);
}
}
JUnit 5 is more modern and flexible, recommended for new projects, but JUnit 4 is still widely used and supported.