Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jUnit testing two boolean arrays

Tags:

java

junit

I just noticed that jUnit 4.8.1 does not include support for testing two boolean arrays for equality. There are tons of other assertArrayEquals but none to take in two boolean arrays.

Is there a proper way to do this? My current thinking is that I'd have to iterate over an array and use something like

Assert.assertTrue(arrayOne[i] == arrayTwo[i]);

Is there a cleaner way to do this?

like image 606
Mike Megally Avatar asked Sep 19 '12 18:09

Mike Megally


2 Answers

You can use Arrays.equals() to compare the two arrays, then assert that they are equivalent.

Assert.assertTrue(Arrays.equals(arrayOne, arrayTwo));

Arrays.equals() checks the length and each element in the array, so you won't have to worry about iterating over each array.

There is also Assert.assertArrayEquals, which will give you the exact position that the arrays differed at.

Example: for a test written as such:

@Test
public void doArrayTest() {
    int[] foo = {1, 2, 3};
    int[] bar = {4, 5, 6};
    assertArrayEquals(foo, bar);
}

The result would be:

arrays first differed at element [0]; expected:<1> but was:<4>

Expected :1
Actual   :4
like image 136
Makoto Avatar answered Nov 15 '22 21:11

Makoto


The functionality has been added in JUnit 4.12, which was released in Dec. 2014.

assertArrayEquals(boolean[] expecteds, boolean[] actuals)
assertArrayEquals(String message, boolean[] expecteds, boolean[] actuals)

For reference: this the the PR that contains the commit: https://github.com/junit-team/junit/pull/632

like image 27
msteiger Avatar answered Nov 15 '22 23:11

msteiger