java - 如何检查数组是否是二维数组中的元素之一

标签 java junit hamcrest

我试图使用 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/

相关文章:

java - JPype1=0.7.0 : TypeError: Unable to convert str ro java type class java. lang.String

java - org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties

java - 我们能否以类似于静态单例的方式轻松地延迟加载 Java 成员?

java - Junit如何在预期错误时显示详细信息

java - 如何将Powermock与Junit5和JDK11一起使用?

java - 如何断言字符串不为空

java - 使用 hamcrest contains() 方法比较两个集合

java - hamcrest 中的递归 SamePropertyValuesAs 匹配器

java - Spring bean,XmlWebApplicationContext 中的生命周期(Web 上下文)

java - org.springframework.beans.NotReadablePropertyException :