2014-12-02 109 views
0

我有一個方法返回數組Sighting []。在我的單元測試中,索引[0]處應該有一個元素(element1)。junit我如何斷言我的方法返回一個特定的數組

我的問題是,我如何建立我的聲明來反映這一點?我需要斷言由我的getMostOfSpecies方法返回的數組在第一個索引值處包含element1。

我的(失敗的)測試看起來像這樣

@Test 
public void getMostOfSpeciesTest() 
{ 
    try { 
     birdList1.remember(sighting5); 
     birdList1.remember(sighting6); 
     birdList1.remember(sighting7); 
     birdList1.remember(sighting8); 
     assertEquals(birdList1.getMostOfSpecies("SOBI"), Sighting[???what to put here???]); 
    } 
    catch (Exception e) { 
     fail("Failed" + e.getMessage()); 
    } 
} 

回答

2

你試過Arrays.equals() [1]?確保你重寫Sighting類的equals()方法。

assertTrue(Arrays.equals(birdList1.getMostOfSpecies("SOBI"), yourSightingArray); 

[1] https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

編輯:

如果需要檢查,如果數組包含一個特定的對象,你可能會感興趣的Arrays.binarySearch() [2]或結合Arrays.asList()與李斯特的含有()-方法。所以,你的斷言語句應該看起來像

assertTrue(Arrays.binarySearch(birdList1.getMostOfSpecies("SOBI"), theElementYouExpect) >= 0); 

[2] https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(java.lang.Object[],%20java.lang.Object)

+0

和d,我的方法返回一個數組。我需要測試它是否包含特定元素。 – user3738926 2014-12-02 12:41:44

+0

對不起,你問題的標題是誤導性的「返回一個特定的數組」......但你可以在你的案例中使用Arrays.binarySearch,我想這就是你要找的。我會編輯我的答案。 – a11n 2014-12-02 12:48:23

+0

謝謝。這工作。 – user3738926 2014-12-03 16:17:26

相關問題