How do I use assertions in JUnit?

In JUnit, assertions are used to verify that your code produces the expected result. If an assertion fails, the test fails.

JUnit 5 assertions are provided by the org.junit.jupiter.api.Assertions class.

Basic Example

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void testAddition() {
        int result = 2 + 3;

        assertEquals(5, result);
    }
}

In this example, the test passes because 2 + 3 equals 5.

Common JUnit Assertions

assertEquals()

Use assertEquals() to check whether two values are equal.

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

assertEquals(10, 5 + 5);
assertEquals("Hello", "He" + "llo");

You can also provide a failure message:

assertEquals(10, 5 + 4, "The result should be 10");

assertNotEquals()

Use assertNotEquals() to check that two values are not equal.

import static org.junit.jupiter.api.Assertions.assertNotEquals;

assertNotEquals(10, 5 + 4);

assertTrue() and assertFalse()

Use assertTrue() when a condition should be true.

import static org.junit.jupiter.api.Assertions.assertTrue;

assertTrue(10 > 5);

Use assertFalse() when a condition should be false.

import static org.junit.jupiter.api.Assertions.assertFalse;

assertFalse(10 < 5);

assertNull() and assertNotNull()

Use assertNull() to check that a value is null.

import static org.junit.jupiter.api.Assertions.assertNull;

String name = null;

assertNull(name);

Use assertNotNull() to check that a value is not null.

import static org.junit.jupiter.api.Assertions.assertNotNull;

String name = "Kode Java";

assertNotNull(name);

assertSame() and assertNotSame()

Use assertSame() to check whether two references point to the same object.

import static org.junit.jupiter.api.Assertions.assertSame;

String text = "Java";
String sameText = text;

assertSame(text, sameText);

Use assertNotSame() when two references should not point to the same object.

import static org.junit.jupiter.api.Assertions.assertNotSame;

String first = new String("Java");
String second = new String("Java");

assertNotSame(first, second);

Note that assertEquals() checks object equality, while assertSame() checks object identity.

assertArrayEquals()

Use assertArrayEquals() to compare arrays.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

int[] expected = {1, 2, 3};
int[] actual = {1, 2, 3};

assertArrayEquals(expected, actual);

assertThrows()

Use assertThrows() to verify that a block of code throws an expected exception.

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertThrows;

class NumberParserTest {

    @Test
    void testInvalidNumber() {
        assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt("abc");
        });
    }
}

You can also inspect the thrown exception:

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

NumberFormatException exception = assertThrows(
        NumberFormatException.class,
        () -> Integer.parseInt("abc")
);

assertEquals("For input string: \"abc\"", exception.getMessage());

assertAll()

Use assertAll() to group multiple assertions together. JUnit will run all assertions and report all failures.

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class UserTest {

    @Test
    void testUserDetails() {
        String name = "Alice";
        int age = 25;

        assertAll(
                () -> assertEquals("Alice", name),
                () -> assertEquals(25, age),
                () -> assertTrue(age >= 18)
        );
    }
}

Without assertAll(), the test stops at the first failed assertion.

fail()

Use fail() when a test should fail explicitly.

import static org.junit.jupiter.api.Assertions.fail;

fail("This test should not reach this point");

This is often useful inside conditional logic or exception handling.

Complete Example

import org.junit.jupiter.api.Test;

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

class StringUtilsTest {

    @Test
    void testStringAssertions() {
        String text = "JUnit";

        assertEquals("JUnit", text);
        assertNotEquals("TestNG", text);
        assertTrue(text.startsWith("J"));
        assertFalse(text.isEmpty());
        assertNotNull(text);
    }

    @Test
    void testArrayAssertions() {
        int[] numbers = {1, 2, 3};

        assertArrayEquals(new int[]{1, 2, 3}, numbers);
    }

    @Test
    void testExceptionAssertion() {
        assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt("not-a-number");
        });
    }
}

Using Static Imports

Most JUnit tests use static imports so assertions can be written directly:

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

Then you can write:

assertEquals(5, result);
assertTrue(result > 0);
assertThrows(Exception.class, () -> someMethod());

Instead of:

Assertions.assertEquals(5, result);
Assertions.assertTrue(result > 0);
Assertions.assertThrows(Exception.class, () -> someMethod());

Summary

Common JUnit assertion methods include:

Assertion Purpose
assertEquals(expected, actual) Checks that two values are equal
assertNotEquals(unexpected, actual) Checks that two values are not equal
assertTrue(condition) Checks that a condition is true
assertFalse(condition) Checks that a condition is false
assertNull(value) Checks that a value is null
assertNotNull(value) Checks that a value is not null
assertSame(expected, actual) Checks that two references point to the same object
assertNotSame(unexpected, actual) Checks that two references do not point to the same object
assertArrayEquals(expected, actual) Checks that two arrays are equal
assertThrows(type, executable) Checks that an exception is thrown
assertAll(executables) Groups multiple assertions
fail(message) Fails the test explicitly

In short, assertions are the main way to express what your code is expected to do in a JUnit test.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.