Learn / Programming / Java / Testing with JUnit

Java · Lesson 15 of 15

Testing with JUnit

Write unit tests, assertions and run them with Maven or Gradle.

  • Intermediate
  • 14 min read
  • 3 objectives

Before this lessonLesson 14: Files and I/O

What you will learn

  • Write a JUnit 5 test
  • Use assertions
  • Test exceptions

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

A unit test calls a small piece of code with known input and checks the result. JUnit 5 is the standard framework: it finds methods annotated with @Test, runs them and reports which failed.

Setup

With Maven, add JUnit Jupiter and put tests under src/test/java.

<!-- pom.xml -->
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <version>5.10.2</version>
  <scope>test</scope>
</dependency>

# run
mvn test

Your first test

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

class Calculator {
    int add(int a, int b) { return a + b; }
    int divide(int a, int b) { return a / b; }
}

class CalculatorTest {
    private final Calculator calc = new Calculator();

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

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

Common assertions

  • assertEquals(expected, actual): note the order, expected first.
  • assertTrue / assertFalse for conditions.
  • assertNull / assertNotNull.
  • assertThrows checks that code raises the exception you expect.

Lifecycle and parameterised tests

import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;

class MathTest {
    @BeforeEach
    void setUp() { /* runs before every test */ }

    @ParameterizedTest
    @CsvSource({"1,1,2", "2,3,5", "10,-4,6"})
    void adds(int a, int b, int expected) {
        assertEquals(expected, a + b);
    }
}
Course completeYou finished JavaReview the full course or pick your next one.