On this page
  1. JUnit 5
  2. Overview
  3. Core Annotations & Assertions
  4. Lifecycle & Extension Highlights

JUnit 5

Prev: Gradle | Up: third_party/java | Next: Spring Framework
Rel: Apache Maven, Gradle, Spring Framework
Ref: JUnit 5 User Guide
Tags: #public #prog #java #third-party #testing #tier/core


Overview

JUnit 5 is the standard testing framework for modern Java. It is split into three sub-projects:

Core Annotations & Assertions

Test classes and methods in JUnit 5 do not need to be public (package-private is idiomatic):

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

import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class PriceCalculatorTest {

    private PriceCalculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new PriceCalculator();
    }

    @Test
    @DisplayName("Applies percentage discount and rounds half-up")
    void appliesDiscount() {
        int result = calculator.applyDiscount(1000, 15);
        assertEquals(850, result);
    }

    @Test
    void rejectsNegativePrice() {
        var ex = assertThrows(IllegalArgumentException.class,
            () -> calculator.applyDiscount(-1, 10));
        assertTrue(ex.getMessage().contains("negative"));
    }

    @ParameterizedTest
    @CsvSource({
        "100, 0, 100",
        "100, 50, 50",
        "200, 100, 0"
    })
    void discountTable(int price, int pct, int expected) {
        assertEquals(expected, calculator.applyDiscount(price, pct));
    }

    @Test
    void groupedAssertionsAndTempDir(@TempDir Path tempDir) throws Exception {
        Path file = tempDir.resolve("receipt.txt");
        Files.writeString(file, "total=850");
        assertAll(
            () -> assertTrue(Files.exists(file)),
            () -> assertEquals("total=850", Files.readString(file))
        );
    }

    @Nested
    class WhenCartIsEmpty {
        @Test
        void totalIsZero() {
            assertEquals(0, calculator.totalOf());
        }
    }
}

Lifecycle & Extension Highlights

Linked from

Related notes