218

Is there a concise, built-in way to do equals assertions on two like-typed arrays in JUnit? By default (at least in JUnit 4) it seems to do an instance compare on the array object itself.

EG, doesn't work:

int[] expectedResult = new int[] { 116800,  116800 };
int[] result = new GraphixMask().sortedAreas(rectangles);
assertEquals(expectedResult, result);

Of course, I can do it manually with:

assertEquals(expectedResult.length, result.length);
for (int i = 0; i < expectedResult.length; i++)
    assertEquals("mismatch at " + i, expectedResult[i], result[i]);

..but is there a better way?

mBria
  • 2,412
  • 2
  • 15
  • 11

8 Answers8

398

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.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • 1
    but all you get when it fails for different length is `java.lang.AssertionError: array lengths differed, expected.length=6 actual.length=7`. As most JUnit failure messages it's not so helpful...I advise using some assertion framework – user1075613 Nov 30 '18 at 20:47
  • 1
    @user1075613 - I find it helpful. We asserted the arrays were equal, they're not, and we're given an indication why. From there, we can set a breakpoint, and examine the arrays in detail. – Andy Thomas Dec 01 '18 at 00:03
  • 1
    right, it's - a bit - helpful. However as you point it out, the instant you have this message you ask yourself "why it's not the same length?" so you want to check the content. Why losing time with a debugger when a good error message could tell it directly? (sure you still need the debugger sometimes but most of the time you don't) – user1075613 Dec 02 '18 at 01:28
  • You can submit issues to [JUnit's issue tracking system](https://github.com/junit-team/junit4/issues). Bear in mind, though, that 1) failing fast, in O(1), can be an advantage, 2) the assertion failure output should not be O(n). The JUnit issue tracking system is a better forum for further discussion. – Andy Thomas Dec 02 '18 at 16:14
  • How do you assert that the arrays are *not* equal element-by-element? – Snackoverflow May 23 '20 at 19:26
  • 1
    @anddero - `Assert.assertFalse( Arrays.equals( expectedResult, result ))`. – Andy Thomas May 24 '20 at 13:12
  • @AndyThomas That's not the JUnit way. When comparing two files and the assertion would fail, it would not tell you at what position there is a wrong byte. It would just say "assertion failed". – Snackoverflow May 25 '20 at 08:25
  • @anddero - I may have misunderstood. Are you asking how to test that *every* corresponding pair of elements is unequal? That's worth asking as a separate question. – Andy Thomas May 25 '20 at 13:23
  • @AndyThomas No, I was actually asking for the exact opposite of `assertArrayEquals` which would be `assertArrayNotEquals` (it does not exist). But I just realized, when testing for inequality, the meaning of "assertion failed" is enough, because all the elements are equal, so there is no need for a comparison output. So you actually answered my question with `Arrays.equals`. – Snackoverflow May 26 '20 at 07:27
42

You can use Arrays.equals(..):

assertTrue(Arrays.equals(expectedResult, result));
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 20
    What stinks about that though is you get NO data about what went wrong when it fails. – mBria Nov 19 '10 at 18:57
  • 8
    Nice when you are on an older junit version (like on Android) – Zitrax Dec 14 '13 at 20:48
  • 4
    If you want to see which bytes don't match you can convert them to string: assertEquals(Arrays.toString(expectedResult), Arrays.toString(result)); – Erdem Dec 03 '15 at 12:12
24

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.

csharpfolk
  • 4,124
  • 25
  • 31
  • 1
    Note, however, that `assertEquals( Arrays.toString( new String[]{ "artiforg", "blobel", "kipple", "tench" } ), Arrays.toString( new String[]{ "artiforg", "blobel, kipple", "tench" } ) );` will pass. (The first array consists of three strings, the second of four strings.) – z32a7ul Jun 02 '22 at 07:46
17

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

Michael Brewer-Davis
  • 14,018
  • 5
  • 37
  • 49
  • 1
    Hm, I don't see any 'assertArrayEquals' in my 'junit.framework.Assert'? – mBria Nov 19 '10 at 18:57
  • 4.8.1 is what I have, and what appears to be the latest available via Maven (http://grepcode.com/search?query=junit+4.9&start=0&entity=type&n=). Is it only in 4.8.2 or 4.9? – mBria Nov 29 '10 at 16:41
16

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

import org.junit.jupiter.api.Assertions;

Assertions.assertArrayEquals(resultArray,actualResult);
Pravanjan
  • 698
  • 7
  • 16
5

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>]
winstanr
  • 51
  • 1
  • 4
4

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.

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80
1

Class Assertions in org.junit.jupiter.api

Use:

public static void assertArrayEquals(int[] expected,
                                     int[] actual)
Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208