2017-07-27 92 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; 
} 
相關問題