Skip to content
AgileLogics
5 min read

Unit Testing with JUnit

Prerequisites: Build tools: Maven and Gradle

JUnit 5 is the standard testing library — a test method is any method annotated @Test that makes assertions about expected behavior.

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

class CalculatorTest {
    @Test
    void addsTwoNumbers() {
        Calculator calc = new Calculator();
        assertEquals(5, calc.add(2, 3));
    }

    @Test
    void divisionByZeroThrows() {
        Calculator calc = new Calculator();
        assertThrows(ArithmeticException.class, () -> calc.divide(1, 0));
    }
}

A build tool runs every @Test-annotated method automatically (mvn test / gradle test) and reports which passed or failed.

Common mistakes

  • Writing a test that depends on another test having already run (e.g. shared mutable state) — each @Test method should be able to run independently, in any order.