To say that code "works" it needs to be verified. JUnit 5 is Java's de facto standard testing framework, providing a short and clear annotation-based API.
Learning Objectives
- Know the location of
src/test/javain the Maven project - Use
@Test,@BeforeEach,@AfterEach,@DisplayName - Know the difference between
assertEquals/assertTrue/assertThrows - Run the test with
mvn test
Key concepts
1) Maven dependencies
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.5</version>
<scope>test</scope>
</dependency>
scope=test is not included in the operating code.
2) Basic testing
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void add returns the sum of two numbers () {
assertEquals(5, new Calculator().add(2, 3));
}
}
3) Life cycle
@BeforeEach void setUp() { ... } //Run before each @Test
@AfterEach void tearDown() { ... } //Run after each @Test
@BeforeAll static void all() { ... } //Once at the start of the entire class
@AfterAll static void clean() { ... } //Once at the end of the entire class
4) Exception testing
@Test
void zero_division() {
assertThrows(ArithmeticException.class,
() -> new Calculator().divide(10, 0));
}
5) mvn test
cd 22_JUnit_test
mvn test
JUnit 5 automatically discovers and executes it and outputs the results.
See as example
Example 1 — Calculator.java: Operational code
package com.codingnow.lecture.modern22;
public class Calculator {
public int add(int a, int b) { return a + b; }
public int subtract(int a, int b) { return a - b; }
public int divide(int a, int b) {
if (b == 0) throw new ArithmeticException("/ zero");
return a / b;
}
}
Example 2 — CalculatorTest.java: The most basic test
package com.codingnow.lecture.modern22;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
Calculator calc = new Calculator();
@Test
@DisplayName("add returns the sum of two numbers")
void add returns_sum() {
assertEquals(5, calc.add(2, 3));
assertEquals(0, calc.add(-1, 1));
}
@Test
void divide_by_zero() {
assertThrows(ArithmeticException.class, () -> calc.divide(10, 0));
}
}
mvn test execution results (partial)
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Example 3 — FixtureTest.java: Lifecycle
package com.codingnow.lecture.modern22;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FixtureTest {
Calculator calc;
@BeforeEach
void setUp() {
calc = new Calculator();
System.out.println("(setUp)");
}
@AfterEach
void tearDown() {
System.out.println("(tearDown)");
}
@Test
void test_add() { assertEquals(7, calc.add(3, 4)); }
@Test
void test_sub() { assertEquals(1, calc.subtract(4, 3)); }
}
(setUp) and (tearDown) are displayed on the console for each test.
Example 4 — AssertionsTest.java: Various assertions
package com.codingnow.lecture.modern22;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class AssertionsTest {
@Test
void variety() {
assertTrue(2 + 2 == 4);
assertFalse("hi".isEmpty());
assertNotNull("");
assertNull(null);
assertArrayEquals(new int[]{1, 2, 3}, new int[]{1, 2, 3});
assertIterableEquals(List.of("a"), List.of("a"));
}
}
Common Mistakes
- Add JUnit dependency to
compilescope → operation jar becomes bloated - Write the
@Testmethod only aspublic(in 5, bothpackage-privateorpublicare OK, onlyprivateis not OK) - Dependency between tests (results of one test affect other tests)
- Change the argument order like
assertEquals(actual, expected)(correct answer first) - Satisfaction by directly catching exceptions with try/catch → Use
assertThrows
Cleanup
- Start automated verification with JUnit 5 + Maven
- The
@Testmethod is small and only verifies one thing. - Separate common initialization with
@BeforeEach - Verification of exception flow diagram with
assertThrows
Try it yourself
cd 05_Modern_Java/22_JUnit_Test
mvn test