我试图使用 Hamcrest 库提供的标准 Collection.isIn 匹配器断言字符串元素数组是二维数组的元素之一。不幸的是收到以下断言异常:
java.lang.AssertionError:
Expected: one of {["A", "B", "C"], ["A", "B", "C"]}
but: was ["A", "B", "C"]
代码:
String[][] expected = new String[][] { { "A", "B", "C" }, { "A", "B", "C" } };
String[] actual = new String[] { "A", "B", "C" };
assertThat(actual, isIn(expected));
我可以以这种方式验证使用 hamcrest 吗?或者我是否需要为给定场景创建自己的匹配器?
最佳答案
问题是,当对象是数组时,Object.equals()
不会执行您可能期望的操作。您可能已经知道,您必须使用 Arrays.equals() - 但 Hamcrest isIn() 不允许这样做。
可能最简单的解决方案是转换为 List
,即使只是为了测试 - 因为 List.equals()
按照 Hamcrest 的预期工作:
...
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)));
关于java - 如何检查数组是否是二维数组中的元素之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45354657/