2011-11-13 4 views
0

문자열 번호 쌍에 대한 클래스가 있습니다. 이 클래스는 compareTo 메소드가 구현되어 있습니다.프리미티브가 아닌 템플릿 매개 변수가있는 컬렉션이있는 AssertEquals

다른 클래스의 메소드는 쌍 유형의 요소 콜렉션을 리턴합니다.

나는이 방법에 단위 테스트를 수행하고 싶었, 따라서 다음 썼다 :

@Test 
public void testWeight() { 

    Collection<StringNumber<BigDecimal>> expected = new Vector<StringNumber<BigDecimal>>(); 
    expected.add(new StringNumber<BigDecimal>("a", BigDecimal.ONE)); 
    expected.add(new StringNumber<BigDecimal>("b", BigDecimal.ONE)); 

    Collection<StringNumber<BigDecimal>> actual = new Vector<StringNumber<BigDecimal>>(); 
    expected.add(new StringNumber<BigDecimal>("a", BigDecimal.ONE)); 
    expected.add(new StringNumber<BigDecimal>("b", BigDecimal.ONE)); 

    //Collection<StringNumber<BigDecimal>> actual = A.f(); 

    assertEquals(expected, actual); 
} 

그러나 당신이 볼 수 있듯이, 주장이 컬렉션의 요소가 동일하더라도 실패합니다. 그 이유는 무엇일까요?

내가 오류가 나에게 장면을하지 않습니다

java.lang.AssertionError: expected: java.util.Vector<[a:1, b:1]> but was: java.util.Vector<[a:1, b:1]>

입니다.

답변

1

StringNumber 클래스는 equals() 메서드가 필요합니다. 그 때 그것은 작동 할 것이다.

@Override 
public boolean equals(Object o) { 
    if (this == o) { 
     return true; 
    } 
    if (!(o instanceof StringNumber)) { 
     return false; 
    } 
    StringNumber that = (StringNumber) o; 
    if (number != null ? !number.equals(that.number) : that.number != null) { 
     return false; 
    } 
    return !(string != null ? !string.equals(that.string) : that.string != null); 

} 

@Override 
public int hashCode() { 
    int result = string != null ? string.hashCode() : 0; 
    result = 31 * result + (number != null ? number.hashCode() : 0); 
    return result; 
} 

몇몇 발언 :이 클래스를 가정하면 (내 IDE에 의해 자동 생성) stringnumber 필드 포함

  • Vector 년대 동일한 (이유는 오래된 데이터 구조를 사용하는)을 if :
  • 최우선 equals()이 필요한 이유

both [...] have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)) .)

.

관련 문제