Unit Testing with JUnit

Site Admin · 11 Sep 2026 · 7 views

Unit Testing with JUnit

Verifying a Single Unit

A unit test verifies one function or class in isolation, feeding it controlled inputs and checking the outputs. JUnit is the standard framework for this in Java, Spring Boot, and many JVM projects. The pattern is universal: each test method states a behavior, calls the unit, and asserts the result.

Your First JUnit Test

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

class CalculatorTest {

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

The @Test annotation marks the method as a test. assertEquals compares the expected value with the actual result. A passing assertion turns the test green; a mismatch fails it with a readable diff.

Lifecycle and Setup

Tests that share setup use @BeforeEach, which runs before every test method so each test starts from a clean state. This isolation is essential: a test that depends on another test's leftovers is a test that fails at random.

class OrderTest {
    private Order order;

    @BeforeEach
    void setUp() {
        order = new Order("A100", 3);
    }

    @Test
    void totalIsPriceTimesQuantity() {
        assertEquals(9.99 * 3, order.total(), 0.001);
    }
}

Note the extra argument: for floating-point comparisons, JUnit's overloaded assertEquals takes a delta for the allowable difference, because exact float equality is unreliable.

Assertions You Will Use Daily

Beyond assertEquals: assertTrue and assertFalse check booleans, assertNull and assertNotNull check presence, assertThrows confirms an exception type, and assertTimeout detects slow operations. Collect several conditions in one test only when they describe the same behavior.

Naming and Structure

Name tests after the behavior, not the method: addsTwoNumbers, not testAdd. Follow the arrange (set up), act (call), assert (verify) structure inside each test. Tests written this way read like documentation and fail with useful messages.

Key Points

  • Unit tests verify one unit with controlled inputs and expected outputs.
  • @Test marks a test method; assertEquals checks equality.
  • @BeforeEach sets up a clean state for every test.
  • Use deltas for float comparisons and assertThrows for errors.
  • Name tests for behavior and follow arrange, act, assert.
Share this post:

Comments (0)

Please login or register to comment.