JUnit 5 Basics

Why Unit Tests

A unit test checks one small piece of code (a method or class) in isolation, in milliseconds. A good test suite catches bugs before users do, lets you refactor safely, and documents how the code should behave. Every serious Java team runs tests on each commit in CI.

JUnit 5 (JUnit Jupiter) is the standard framework. Spring Boot's spring-boot-starter-test already includes JUnit 5, Mockito and AssertJ.

Setup (Maven)

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.11.3</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>5.14.2</version>
    <scope>test</scope>
</dependency>

Tests live in src/test/java, mirroring the package of the class under test. Name them XxxTest.

First Test

// src/main/java/com/shop/PriceCalculator.java
public class PriceCalculator {
    public double withGst(double price) {
        if (price < 0) throw new IllegalArgumentException("price must be >= 0");
        return Math.round(price * 1.18 * 100) / 100.0;
    }
}

// src/test/java/com/shop/PriceCalculatorTest.java
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;

class PriceCalculatorTest {
    private final PriceCalculator calc = new PriceCalculator();

    @Test
    void addsEighteenPercentGst() {
        assertEquals(118.0, calc.withGst(100));        // expected, actual
    }

    @Test
    @DisplayName("Negative price is rejected")
    void rejectsNegativePrice() {
        IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> calc.withGst(-1));
        assertEquals("price must be >= 0", ex.getMessage());
    }
}

Example

mvn test

Example output

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.shop.PriceCalculatorTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.041 s
[INFO] BUILD SUCCESS