0
0
JUnittesting~5 mins

assertEquals in JUnit

Choose your learning style9 modes available
Introduction

assertEquals checks if two values are the same. It helps confirm your code works as expected.

When you want to check if a method returns the correct number.
When you want to verify that two strings are exactly equal.
When you want to compare expected and actual results in a test.
When you want to confirm that a calculation gives the right answer.
Syntax
JUnit
assertEquals(expected, actual);
assertEquals(String message, expected, actual);

The first form compares expected and actual values.

The second form adds a message shown if the test fails.

Examples
Checks if sum equals 5.
JUnit
assertEquals(5, sum);
Checks if greeting equals "Hello".
JUnit
assertEquals("Hello", greeting);
Checks sum equals 5 and shows message if not.
JUnit
assertEquals("Sum should be 5", 5, sum);
Sample Program

This test checks if the add method returns 5 when adding 2 and 3.

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

public class CalculatorTest {

    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 3);
        assertEquals(5, result, "2 + 3 should be 5");
    }
}

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}
OutputSuccess
Important Notes

assertEquals uses equals() method for objects, so it works well with strings and custom objects if equals is overridden.

Order matters: first argument is expected, second is actual result.

Use the message argument to make failures easier to understand.

Summary

assertEquals compares expected and actual values in tests.

It helps catch mistakes by failing tests when values differ.

Adding a message helps explain test failures.