Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing arrays in JUnit assertions, concise built-in way?

People also ask

How do you assert an array in JUnit?

The 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. Let's first create Book, BookService classes, and then we will write JUnit test cases to use the assertArrayEquals() method.

Which of the following methods would you use for comparing arrays in JUnit?

The assertArrayEquals() method will test whether two arrays are equal to each other.

How do I compare two lists in JUnit?

Using JUnit We can use the logic below to compare the equality of two lists using the assertTrue and assertFalse methods. In this first test, the size of both lists is compared before we check if the elements in both lists are the same. As both of these conditions return true, our test will pass.


Use org.junit.Assert's method assertArrayEquals:

import org.junit.Assert;
...

Assert.assertArrayEquals( expectedResult, result );

If this method is not available, you may have accidentally imported the Assert class from junit.framework.


You can use Arrays.equals(..):

assertTrue(Arrays.equals(expectedResult, result));

I prefer to convert arrays to strings:

Assert.assertEquals(
                Arrays.toString(values),
                Arrays.toString(new int[] { 7, 8, 9, 3 }));

this way I can see clearly where wrong values are. This works effectively only for small sized arrays, but I rarely use arrays with more items than 7 in my unit tests.

This method works for primitive types and for other types when overload of toString returns all essential information.


Assert.assertArrayEquals("message", expectedResult, result)


Using junit4 and Hamcrest you get a concise method of comparing arrays. It also gives details of where the error is in the failure trace.

import static org.junit.Assert.*
import static org.hamcrest.CoreMatchers.*;

//...

assertThat(result, is(new int[] {56, 100, 2000}));

Failure Trace output:

java.lang.AssertionError: 
   Expected: is [<56>, <100>, <2000>]
   but: was [<55>, <100>, <2000>]

I know the question is for JUnit4, but if you happen to be stuck at JUnit3, you could create a short utility function like that:

private void assertArrayEquals(Object[] esperado, Object[] real) {
    assertEquals(Arrays.asList(esperado), Arrays.asList(real));     
}

In JUnit3, this is better than directly comparing the arrays, since it will detail exactly which elements are different.


JUnit 5 we can just import Assertions and use Assertions.assertArrayEquals method

import org.junit.jupiter.api.Assertions;

Assertions.assertArrayEquals(resultArray,actualResult);