Lesson 41: Unit Testing with JUnit 5

11 Aug 2026 1 min Swarnil Singhai

Automated tests verify behavior stays correct as code changes — JUnit is the standard framework for writing and running them in Java.

Real-time example

A Calculator.divide() method gets a test asserting correct output and a test asserting it throws on divide-by-zero.

class CalculatorTest {
    @Test
    void dividesCorrectly() {
        assertEquals(5, Calculator.divide(10, 2));
    }
    @Test
    void throwsOnDivideByZero() {
        assertThrows(ArithmeticException.class,
            () -> Calculator.divide(10, 0));
    }
}

What's happening

assertThrows both runs the code and asserts the exception type — a single line covers the entire failure scenario.

Tests are documentation that can't go stale — they describe exactly how the code is supposed to behave, and fail loudly if it doesn't.

Advertisement