简体   繁体   中英

How to make two objects equal to 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)));

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 fails at assertEquals(i, i2); I've tried to override toString() method, but that didn't help. It was actually written that Item(id=1) was expected and it got exactly Item(id=1) but there is still a problem.

I saw suggestions in other threads to override the equals method but don't really know how to do that.

You need to override the equals(Object) method:

@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 Java's contract regarding equals(Object) and hashCode() , you'd need to override that too. 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;
}

These are naive implementations assuming none of your members can be null . 这些都是天真的实现,假设您的成员都不能为null

You need to implement Object.equals method to provide meaningful equality test, ie using the attributes of your object. Also best practice dictates you should also implement hashCode() which is typically needed when using your object to behave correctly as a key in a HashMap

I see you implemented java.lang.Comparable, this is only typically used to allow sorting using Collections.sort.

It is a shame the Javadoc for Assert.assertEquals makes no mention of Object.equals() for new Java programmers.

You should override equals method. (and also the hashCode)

Thanks for the answers. Actually all I needed was to generate equals() and hashode() methods to include only id field on this occasion. I did this by selecting my constructor Source > Generate hashCode() and equals()...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM