How do I test expected values with assertEquals()?

In JUnit, you use assertEquals() to test whether an actual value matches an expected value.

The basic syntax is:

assertEquals(expectedValue, actualValue);

The first argument is what you expect.
The second argument is what your code actually produced.

Basic Example

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

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

        assertEquals(5, result);
    }
}

In this example:

assertEquals(5, result);

means:

I expect the result to be 5.

If result is 5, the test passes.
If result is anything else, the test fails.

Example with Strings

import org.junit.jupiter.api.Test;

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

class GreetingTest {

    @Test
    void shouldReturnGreetingMessage() {
        String message = "Hello, Java";

        assertEquals("Hello, Java", message);
    }
}

Using a Failure Message

You can add a custom message that appears when the test fails:

assertEquals(10, result, "The result should be 10");

Example:

import org.junit.jupiter.api.Test;

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

class MathTest {

    @Test
    void shouldMultiplyNumbers() {
        int result = 4 * 3;

        assertEquals(12, result, "4 multiplied by 3 should be 12");
    }
}

Common Mistake

Be careful with the order:

assertEquals(expected, actual);

Good:

assertEquals(100, total);

Less clear:

assertEquals(total, 100);

JUnit will still compare the values, but failure messages are easier to understand when the expected value comes first.

Example with a Method

Suppose you have this class:

class Calculator {

    int add(int a, int b) {
        return a + b;
    }
}

You can test it like this:

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void addShouldReturnSum() {
        Calculator calculator = new Calculator();

        int actual = calculator.add(2, 3);

        assertEquals(5, actual);
    }
}

Summary

Use assertEquals() like this:

assertEquals(expected, actual);

For example:

assertEquals(5, result);
assertEquals("Alice", name);
assertEquals(100.0, price);

assertEquals() is one of the most common JUnit assertions because it clearly checks whether your code returned the value you expected.