2015-07-03 59 views
0

我想測試我的insert方法。 insert方法只是將該對象添加到列表中。但是,當我使用assertEquals時,它似乎是比較對象而不是對象的內容。assertEquals比較對象id而不是對象的內容?

有沒有辦法比較存儲在ArrayList中的用戶定義對象的元素?

@Test 
public void testInsert() { 
    // Method answer 
    Interval newInterval = new Interval(1, 20); 
    ArrayList<Interval> emptyInterval = new ArrayList<Interval>(); 
    ArrayList<Interval> returnedAnswer = Solution.insert(emptyInterval, newInterval); 

    // Expected answer 
    ArrayList<Interval> expected = new ArrayList<Interval>(); 
    //expected.add(newInterval); // This will pass 
    expected.add(new Interval(1, 20)); // This will fail 

    assertEquals(expected, returnedAnswer); 
} 
通過調用其 equals方法的對象

enter image description here

回答

2

assertEquals測試平等。這意味着對象必須具有該方法的充分實現。它看起來像Interval沒有它。因此您必須實施Interval.equals(Object)

如果您不想覆蓋equals,則可以使用Hamcrest匹配器。但是您也需要NitorCreations matcher庫的匹配器reflectEquals

assertThat(returnedAnswer, contains(
    reflectsEquals(new Interval(1, 20)))); 

也許AssertJ提供了類似的斷言,但你必須去尋找自己,因爲我很少使用AssertJ。

+0

太棒了!實現了我自己的'Interval.equals(Object)'並且像魅力一樣工作。但是,還有其他方法可以做到嗎?因爲如果我有許多用戶定義的類,那麼覆蓋每個類的'euqals'會非常麻煩。 – LuckyGuess

+1

我擴展了我的答案。 –

+0

謝謝Stefan的幫助。我之前沒有使用Hamcrest,也是JUnit的新成員。我將不得不更多地關注這一點。現在,我想我會堅持重寫'equals'。 – LuckyGuess