Using hamcrest matchers with primitive type arrays

Here is my solution it also uses Apache Commons ArrayUtils#toObject

With the imports

import static org.apache.commons.lang3.ArrayUtils.toObject;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.hasItemInArray;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;

You can write readable tests like

@Test
void primitiveArrayTest() {
    int[] actual = new int[]{1, 2, 3};

    assertThat(toObject(actual), is(arrayContaining(1, 2, 3)));
    assertThat(toObject(actual), is(arrayContainingInAnyOrder(2, 3, 1)));
    assertThat(toObject(actual), hasItemInArray(2));
    assertThat(toObject(actual), is(not(arrayContaining(-5))));
}

The is is just used to improve the readability.


AFAIK there isn't an automatic way of achieving this. If you can make use of 3rd party libraries you might want to check out the Apache Commons Lang library which provides an ArrayUtils class with a conversion method:

Integer[] toObject(int[] array)

int[] values = someMethodCall();
Integer[] objValues = ArrayUtils.toObject(values);
assertThat(objValues , hasItemInArray(1));