JUnit – assertEquals()

In this tutorial, you will learn about the assertEquals() method in JUnit.

assertEquals() method is one of the most commonly used assertions for testing equality. We will explore its usage, understand its parameters, and go through various examples to see how it can be applied effectively in different scenarios.

The assertEquals() method is part of the Assertions class in JUnit, which provides a suite of methods to validate the expected outcomes of tests. It is mainly used to compare the expected and actual values of objects or primitives. If the two values do not match, the test fails, and JUnit provides a detailed message indicating the discrepancy.


Understanding assertEquals()

The assertEquals() method checks whether two values are equal. If they are not, the test fails, and a failure message is displayed. It can compare both primitive types (like integers and booleans) and objects. Here’s the method signature for reference:

</>
Copy
static void assertEquals(Object expected, Object actual);
static void assertEquals(Object expected, Object actual, String message);

The first method compares the expected and actual values, while the second includes an optional custom message for better debugging. JUnit will pass the test if the two values are equal; otherwise, it will fail.


Basic Usage of assertEquals()

Let’s start with a simple example to understand the basic usage of assertEquals(). Here, we test a method that adds two numbers:

</>
Copy
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

class CalculatorTest {

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

    @Test
    void testAddition() {
        CalculatorTest calculator = new CalculatorTest();
        int expected = 5;
        int actual = calculator.add(2, 3);
        assertEquals(expected, actual, "2 + 3 should equal 5");
    }
}

Explanation:

  • Arrange: We create an instance of the CalculatorTest class and define the expected result (5).
  • Act: We call the add method with inputs 2 and 3.
  • Assert: We use assertEquals() to check if the actual result matches the expected result. If not, the test will fail with the provided custom message.

Using assertEquals() with Strings

The assertEquals() method can also be used to compare strings. Let’s test a method that formats a full name:

</>
Copy
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

class StringTest {

    String formatName(String firstName, String lastName) {
        return firstName + " " + lastName;
    }

    @Test
    void testFormatName() {
        StringTest stringTest = new StringTest();
        String expected = "John Doe";
        String actual = stringTest.formatName("John", "Doe");
        assertEquals(expected, actual, "The full name should be 'John Doe'");
    }
}

Key Takeaway:

The comparison is case-sensitive and whitespace-sensitive, so any difference (e.g., “john doe” vs. “John Doe”) will cause the test to fail.


Using assertEquals() with Arrays

The assertEquals() method is not suitable for comparing arrays directly. For arrays, use assertArrayEquals(). Let’s see why:

</>
Copy
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;

class ArrayTest {

    int[] getNumbers() {
        return new int[]{1, 2, 3};
    }

    @Test
    void testArrayEquality() {
        int[] expected = {1, 2, 3};
        int[] actual = getNumbers();

        // Fails: assertEquals does not compare arrays correctly
        // assertEquals(expected, actual);

        // Passes: Use assertArrayEquals for array comparison
        assertArrayEquals(expected, actual, "The arrays should be equal");
    }
}

Why?

When comparing arrays, assertEquals() checks object references, not content. Use assertArrayEquals() to compare array elements.


Handling Floating-Point Numbers

Floating-point numbers (e.g., float, double) often have precision issues, so assertEquals() provides an overloaded method with a delta value to define the acceptable error margin:

</>
Copy
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

class FloatingPointTest {

    @Test
    void testFloatingPointEquality() {
        double expected = 0.3;
        double actual = 0.1 + 0.2;
        double delta = 0.0001;

        assertEquals(expected, actual, delta, "The result should be approximately 0.3");
    }
}

Key Point:

The delta specifies the allowed difference between the expected and actual values, accounting for precision errors.


Using Custom Messages in assertEquals()

Adding custom messages helps in debugging when a test fails. These messages should be meaningful and provide context:

</>
Copy
@Test
void testWithCustomMessage() {
    int expected = 10;
    int actual = 5 + 5;
    assertEquals(expected, actual, "Expected sum: " + expected + ", but got: " + actual);
}

Uses of Custom Messages:

The custom message clearly indicates what went wrong, making it easier to diagnose issues.


Common Mistakes with assertEquals()

  • Comparing Arrays: Use assertArrayEquals() instead of assertEquals().
  • Null Checks: Use assertNull() or assertNotNull() for null validations.
  • Floating-Point Precision: Always specify a delta when comparing floating-point numbers.
  • Incorrect Order of Parameters: The first parameter should be the expected value, and the second should be the actual value.

Conclusion

The assertEquals() method is an essential tool in JUnit for verifying the correctness of your code. Whether you’re comparing integers, strings, or floating-point numbers, understanding its nuances and applying it correctly ensures more reliable and maintainable tests. By incorporating meaningful messages and avoiding common mistakes, you can maximize the effectiveness of your test cases.