assertArraysEquals example

In this post under Junit 5, I will explain with example the purpose of “assertArraysEquals” method.

We can use the “assertArraysEquals” method to assert whether two arrays are equal or not.

Below is the complete main code for your reference.

Main Class

package package15;

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

import org.junit.jupiter.api.Test;

public class Example15 {
@Test
public void testTwoArrays() {
int[] array1 = {0,2,4,6};
int[] array2 = {0,2,5,7};
int[] array3 = {0,2,4,6};

assertAll(() -> {
assertArrayEquals(array1, array2, "array1 and array2 are not equal");
},
() -> {
assertArrayEquals(array1, array3, "array1 and array3 are equal");
},
() -> {
assertArrayEquals(array2, array3, "array2 and array3 are not equal");
});
}
}

In the code, first and third “assertArrayEquals” fails whereas the second one passes.

The Junit 5 framework has several overloaded versions of “assertArrayEquals” method supporting different data types.

In this way we can use “assertArrayEquals” method for comparing two arrays.

Leave a comment