[英]How to make two objects equal to pass assertEquals()?
所以我有這個代碼:
Item i = new Item(ID, TITLE, DESCRIPTION) { };
Item i2 = new Item(ID, "", "") { };
assertEquals("Item(id=1)", i.toString());
assertEquals("Item(id=1)", i2.toString());
assertNotSame(i, i2);
assertEquals(i, i2);
assertThat(0, not(equalTo(i.compareTo(i2))));
Item i3 = new Item(BigInteger.TEN, "", "") { };
assertEquals("Item(id=10)", i3.toString());
assertNotSame(i, i3);
assertThat(i, not(equalTo(i3)));
還提供:
@Override
public final int compareTo(final Item o) {
int c = o.title.compareTo(title);
if (c == 0) {
c = o.id.compareTo(id);
}
return c;
}
它傳遞assertNotSame(i, i2);
但在assertEquals(i, i2);
失敗assertEquals(i, i2);
我試圖覆蓋toString()
方法,但這沒有幫助。 實際上寫的是Item(id=1)
是預期的,它完全是Item(id=1)
但仍然存在問題。
我看到其他線程中的建議覆蓋了equals
方法,但實際上並不知道如何做到這一點。
您需要覆蓋equals(Object)
方法:
@Override
public boolean equals (Object o) {
if (!o instanceof Item) {
return false;
}
Item other = (Item)o;
return getId().equals(other.getId()) &&
getTitle().equals(other.getTitle()) &&
getDescription().equals(other.getDescription());
}
為了不破壞Java關於equals(Object)
和hashCode()
的契約,你也需要覆蓋它。 例如:
@Override
public int hashCode() {
final int prime = 31;
result = prime * result + getId().hashCode();
result = prime * result + getTitle().hashCode();
result = prime * result + getDescription().hashCode();
return result;
}
注意:這些都是天真的實現,假設您的成員都不能為null
。
您需要實現Object.equals方法以提供有意義的相等性測試,即使用對象的屬性。 此外,最佳實踐規定您還應該實現hashCode(),這在使用對象在HashMap中作為鍵正確運行時通常是必需的
我看到你實現了java.lang.Comparable,這通常只用於允許使用Collections.sort進行排序。
令人遺憾的是Assert.assertEquals的Javadoc沒有提及新Java程序員的Object.equals()。
你應該重寫equals方法。 (還有hashCode)
謝謝你的回答。 實際上我只需要生成equals()
和hashode()
方法,在這種情況下只包含id
字段。 我選擇了我的構造函數Source> Generate hashCode()和equals()......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.