0
0
JUnittesting~5 mins

JUnit 4 vs JUnit 5 (Jupiter) differences

Choose your learning style9 modes available
Introduction

JUnit 4 and JUnit 5 are versions of a tool that helps test Java code. Knowing their differences helps you write better tests and use the right features.

When starting a new Java project and choosing a testing framework.
When updating old tests to use newer features and better structure.
When needing better support for modern Java features like lambdas.
When wanting more flexible and powerful test lifecycle controls.
When integrating tests with modern build tools and IDEs.
Syntax
JUnit
JUnit 4 example:

import org.junit.Test;
import static org.junit.Assert.*;

public class ExampleTest {
    @Test
    public void testAddition() {
        assertEquals(5, 2 + 3);
    }
}

JUnit 5 example:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class ExampleTest {
    @Test
    void testAddition() {
        assertEquals(5, 2 + 3);
    }
}

JUnit 5 uses the package org.junit.jupiter.api instead of org.junit.

JUnit 5 test methods can have default (package-private) visibility, no need to be public.

Examples
JUnit 4 test method must be public and annotated with @Test.
JUnit
@Test
public void testMethod() {
    assertTrue(true);
}
JUnit 5 test method can be package-private (no modifier) and uses @Test from Jupiter.
JUnit
@Test
void testMethod() {
    assertTrue(true);
}
JUnit 4 uses @Before for setup before each test.
JUnit
@Before
public void setup() {
    // runs before each test in JUnit 4
}
JUnit 5 uses @BeforeEach instead of @Before.
JUnit
@BeforeEach
void setup() {
    // runs before each test in JUnit 5
}
Sample Program

This JUnit 5 test class has two simple tests for addition and subtraction. Each test checks if the math result is correct.

JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {

    @Test
    void additionTest() {
        int result = 2 + 3;
        assertEquals(5, result, "2 + 3 should equal 5");
    }

    @Test
    void subtractionTest() {
        int result = 5 - 3;
        assertEquals(2, result, "5 - 3 should equal 2");
    }
}
OutputSuccess
Important Notes

JUnit 5 is modular and supports running JUnit 4 tests via a vintage engine.

JUnit 5 supports lambda expressions for assertions, making tests cleaner.

JUnit 5 has better support for tagging and filtering tests.

Summary

JUnit 5 is the newer, more flexible version of JUnit with better Java support.

JUnit 4 requires public test methods; JUnit 5 does not.

Annotations like @Before in JUnit 4 are replaced by @BeforeEach in JUnit 5.