Java

JUnit 5 — Basic Test

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
JUnit 5 is the modern standard. `@Test` marks a method as a test; `Assertions.*` provides the assertion API. `@BeforeEach` runs setup before every test.
Java
Raw
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;

class CalculatorTest {

    private Calculator calc;

    @BeforeEach
    void setUp() {
        calc = new Calculator();
    }

    @Test
    void addsPositiveNumbers() {
        assertEquals(5, calc.add(2, 3));
    }

    @Test
    @DisplayName("Subtraction works for negative numbers")
    void subtractsNegatives() {
        assertEquals(-3, calc.subtract(-1, 2));
    }

    @Test
    void throwsOnDivideByZero() {
        var ex = assertThrows(ArithmeticException.class,
            () -> calc.divide(10, 0));
        assertEquals("/ by zero", ex.getMessage());
    }

    @Test
    @Disabled("flaky on CI — see ENG-123")
    void someFlakyTest() { /* ... */ }

    @Test
    void groupedAssertions() {
        assertAll("calculator basics",
            () -> assertEquals(4, calc.add(2, 2)),
            () -> assertEquals(0, calc.subtract(5, 5)),
            () -> assertEquals(6, calc.multiply(2, 3))
        );
    }
}

class Calculator {
    int add(int a, int b)      { return a + b; }
    int subtract(int a, int b) { return a - b; }
    int multiply(int a, int b) { return a * b; }
    int divide(int a, int b)   { return a / b; }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.