How to Use assertArrayEquals in JUnit for Array Comparison
Use
assertArrayEquals in JUnit to check if two arrays are equal by comparing their elements in order. It throws an assertion error if arrays differ in length or content, helping verify array results in tests.Syntax
The assertArrayEquals method compares two arrays element-by-element. It has these common forms:
assertArrayEquals(expectedArray, actualArray)- checks if both arrays are equal.assertArrayEquals(expectedArray, actualArray, message)- same as above but shows a custom message on failure.
Both arrays must be of the same type and length for the assertion to pass.
java
assertArrayEquals(expectedArray, actualArray);
assertArrayEquals(expectedArray, actualArray, "Arrays differ");Example
This example shows how to use assertArrayEquals to test if two integer arrays are equal in a JUnit test method.
java
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class ArrayTest { @Test public void testIntegerArrays() { int[] expected = {1, 2, 3, 4}; int[] actual = {1, 2, 3, 4}; assertArrayEquals(expected, actual, "Integer arrays should be equal"); } @Test public void testStringArrays() { String[] expected = {"apple", "banana"}; String[] actual = {"apple", "banana"}; assertArrayEquals(expected, actual); } }
Output
Tests passed: 2, Failures: 0, Errors: 0
Common Pitfalls
Common mistakes when using assertArrayEquals include:
- Comparing arrays of different lengths, which always fails.
- Using
assertEqualsinstead ofassertArrayEqualsfor arrays, which compares references, not contents. - Not matching array types exactly (e.g., int[] vs Integer[]).
Always use assertArrayEquals for arrays to compare contents properly.
java
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class PitfallTest { @Test public void wrongAssertion() { int[] expected = {1, 2}; int[] actual = {1, 2}; // This will fail because assertEquals compares references // assertEquals(expected, actual); // WRONG // Correct way: assertArrayEquals(expected, actual); } @Test public void differentLengths() { int[] expected = {1, 2}; int[] actual = {1, 2, 3}; // This will fail due to length mismatch // assertArrayEquals(expected, actual); // FAILS } }
Quick Reference
Summary tips for using assertArrayEquals:
- Use it to compare arrays element-wise in tests.
- Works with primitive and object arrays.
- Provide a failure message for clearer test reports.
- Do not use
assertEqualsfor arrays. - Arrays must be the same length and type.
Key Takeaways
Use assertArrayEquals to compare array contents element-by-element in JUnit tests.
Do not use assertEquals for arrays as it compares references, not contents.
Arrays must be the same length and type for assertArrayEquals to pass.
Add a custom message to help identify failures clearly.
assertArrayEquals works for both primitive and object arrays.