I am trying to assert that an array of string elements is one of the elements of a 2-dimensional array using the standard Collection.isIn matcher provided with Hamcrest library. Unfortunately receiving the following assertion exception:
java.lang.AssertionError:
Expected: one of {["A", "B", "C"], ["A", "B", "C"]}
but: was ["A", "B", "C"]
Code:
String[][] expected = new String[][] { { "A", "B", "C" }, { "A", "B", "C" } };
String[] actual = new String[] { "A", "B", "C" };
assertThat(actual, isIn(expected));
Can I validate using hamcrest in such a manner? Or do I need to create my own matcher for the given scenario?
The issue is that Object.equals()
doesn't do what you might expect when the objects are arrays. As you probably already know, you have to use Arrays.equals()
-- but Hamcrest isIn()
does not allow for this.
Probably the simplest solution is to convert to List
even if only for the test -- because List.equals()
works as Hamcrest expects:
...
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.collection.IsIn.in;
...
String[][] expected = new String[][] { { "A", "B", "C" }, { "A", "B", "C" } };
Object[] expectedLists = Arrays.stream(expected).map(Arrays::asList).toArray();
String[] actual = new String[] { "A", "B", "C" };
assertThat(Arrays.asList(actual), is(in(expectedLists)));