How do I make two objects equal pass assertEquals ()?
So, I have this code:
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)));
It is also provided that:
@Override
public final int compareTo(final Item o) {
int c = o.title.compareTo(title);
if (c == 0) {
c = o.id.compareTo(id);
}
return c;
}
It passes assertNotSame(i, i2);
but doesn't work in assertEquals(i, i2);
I tried to override the method toString()
but it didn't help. It actually wrote what was expected Item(id=1)
and it got exactly Item(id=1)
, but the problem still remains.
I've seen suggestions on other threads to override a method equals
, but don't know how.
source to share
You need to override the method 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());
}
In order not to break the Java contract regarding equals(Object)
and hashCode()
, you also need to override this. eg:.
@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;
}
Note: These are naive implementations if none of your members can be null
.
source to share
You need to implement the Object.equals method to provide a meaningful equality test, i.e. using the attributes of your object. Also, best practice dictates that you also implement hashCode (), which is usually needed when your object behaves correctly as a key in a HashMap
I see you have implemented java.lang.Comparable, this is commonly used for sorting with Collections.sort.
Shame on the Javadoc for Assert.assertEquals does not mention Object.equals () for new Java programmers.
source to share