JUnit 5 assertArrayEquals Example

In this article, we will learn how to check two array objects are equal. assertArrayEquals() is static method belongs to JUnit 5 org.junit.jupiter.api.Assertions Class. Note that in JUnit 5 all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.
There are many overloaded version of assertArrayEquals() methods present in org.junit.jupiter.api.Assertions class.
Let me list out tools and technologies that I have used to develop JUnit 5 assertArrayEquals Example.

Tools and Technologies Used

  1. Eclipse photon (only this eclipse version supports JUnit 5)
  2. Maven
  3. JUnit 5
  4. JDK 8 or later
assertArrayEquals() method asserts that two object arrays are equal. If they are not, an AssertionError is thrown. If expected and actual are null, they are considered equal.

assertArrayEquals() Method Example

In this example, we will first create a method to be tested using assertArrayEquals() method. The below method concatenates two String Arrays.
public static String[] concatenateStringArrays(final String[] array1, final String[] array2) {
  if (array1 == null || array1.length == 0) {
    return array2;
  }
  if (array2 == null || array2.length == 0) {
    return array1;
  }

  final String[] newArr = new String[array1.length + array2.length];
  System.arraycopy(array1, 0, newArr, 0, array1.length);
  System.arraycopy(array2, 0, newArr, array1.length, array2.length);
  return newArr;
}
Let's write JUnit test for above method and also use assertArrayEquals() method to assert two object arrays are equal.
package com.javaguides.junit5.assertions;

import static org.junit.Assert.assertArrayEquals;

import org.junit.jupiter.api.Test;

public class JUnit5AssertArrayEqualsDemo {

 public static String[] concatenateStringArrays(final String[] array1, final String[] array2) {
  if (array1 == null || array1.length == 0) {
   return array2;
  }
  if (array2 == null || array2.length == 0) {
   return array1;
  }

  final String[] newArr = new String[array1.length + array2.length];
  System.arraycopy(array1, 0, newArr, 0, array1.length);
  System.arraycopy(array2, 0, newArr, array1.length, array2.length);
  return newArr;
 }

 @Test
 public void testConcatenateStringArrays() {
  final String[] input1 = new String[] { "myString2" };
  final String[] input2 = new String[] { "myString1", "myString2" };

  assertArrayEquals(input1, concatenateStringArrays(input1, null));
  assertArrayEquals(input2, concatenateStringArrays(null, input2));
 }

}

Output

Comments