2017-07-27 95 views
0

我想声明一个字符串元素数组是使用标准Collection.isIn的二维数组元素之一匹配器提供Hamc​​rest库。不幸的是收到以下断言例外:如何检查一个数组是否是二维数组中的一个元素

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以这样的方式?或者我需要为给定的场景创建自己的匹配器?

+1

我提出的问题更容易阅读通过替换短字符串。它不会影响问题或答案。 – slim

回答

3

的问题是,Object.equals()不会做时,对象数组你所期望的是什么。您可能已经知道,您必须使用Arrays.equals() - 但Hamcrest isIn()不允许这样做。

也许是最简单的办法是转换为List即使只为测试 - 因为List.equals()作品Hamcrest预计:

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), isIn(expectedLists)); 
+0

感谢您提供基于列表的解决方案替代hamcrest。 – Vivek

1

您的数组可能包含与expected中的数组相同的内容,但它不是同一个对象。

0

我猜这个问题是因为该方法比较对象,而不是内容。基本上,即使两者具有相同的内容,它们也不是同一个对象。 See here in the docs

而是执行此操作:

String[] actual = new String[]{"A1 C1 E1 F1 J1", "A1 C1 E1 F1 K1", "A1 B1 G1 H1"}; String[][] expected = new String[][]{actual, {"A1 C1 E1 F1 J1", "A1 C1 E1 F1 K1", "A1 B1 G1 H1"}};

1

首先,你会过得更好使用List<>,而不是阵列。其次,是的,如果你坚持使用数组,你将需要编写你自己的'array-contains-element'函数。您可以在数组的主维上使用循环来实现此函数,并调用Arrays.equals()方法来比较两个一维数组的内容。

0

在您的上下文中,collection.IsIn的问题在于您的列表元素是一个数组,它将使用Array#equals来比较每个元素。

更具体地说

// It will print false, because Array.equals check the reference 
// of objects, not the content 
System.out.println(actual.equals(new String[]{"A1 C1 E1 F1 J1", "A1 C1 E1 F1 K1", "A1 B1 G1 H1"})); 

所以我建议创建一个使用满足Arrays.equals从Java自定义匹配。它会为你比较阵列的内容。类似下面的代码:

public boolean matches(Object item) { 
    final String[] actualStringArray = (String [])item; 

    List<String[]> listOfStringArrays = Arrays.asList(expectedStringMatrix); 

    for (String[] stringArray : listOfStringArrays) { 
     // Arrays.equals to compare the contents of two array! 
     if (Arrays.equals(stringArray, actualStringArray)) { 
      return true; 
     } 
    } 
    return false; 
} 
相关问题