k13n k13n - 3 months ago 48
Java Question

Using hamcrest matchers with primitive type arrays

Hamcrest works well for primitive data types due to automatic boxing and unboxing like in this case:

assertThat(1, is(1));


However, I would like to use hamcrest's
hasItemInArray
matcher with a primitive type array like this:

int[] values = someMethodCall();
assertThat(values, hasItemInArray(1));


Since there is no automatic boxing/unboxing for arrays of primitive data types the above code does not compile. Is there any preferred way of accomplishing the above, other than manually converting from
int[]
to
Integer[]
?

Answer

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));
Comments