Sobes.tech
Junior — Middle

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: @BeforeEach instead of @Before, @AfterEach instead of @After, @BeforeAll instead of @BeforeClass, @AfterAll instead of @AfterClass.
    • @Test in JUnit 5 supports new features, such as specifying expected exceptions via assertThrows instead of annotation parameters.
  • 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.

What are the differences between JUnit 4 and JUnit 5… - sobes.tech