EqualsVerifier is a Java library for testing whether equals() and hashCode() implementations satisfy the equality contract. It aims to expose problems that are difficult to cover with manual tests. section 7.6
Use it when ordinary assertions can miss asymmetric or malformed equality. For example, assertNotEquals(obj1, obj2) may exercise the other object's equals() method instead of the implementation under test. section 10.6
Prefer these safeguards around equality implementations:
- Generate equals() and hashCode() with an IDE when appropriate, or use record classes from Java 16 onward. section 7.6
- Use Objects.equals() for nullable fields, then validate the complete implementation with EqualsVerifier. section 7.6
- Use assertFalse(obj1.equals(obj2)) when a direct false result must be checked. section 10.6
A malformed equality implementation
A class that compares attributes to itself instead of the other object, or compares the wrong field, illustrates the kind of defect EqualsVerifier is intended to catch. section 7.6
class MyEntity {
private String name;
private List<String> attributes;
private Object data;
private long timeStamp;
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyEntity other = (MyEntity) o;
return timeStamp == other.timeStamp &&
name.equals(other.name) &&
attributes.equals(attributes) &&
data.equals(other.data);
}
}
Inspect the MyEntity example to see how field-selection and null-handling mistakes can corrupt equality behavior. section 7.6
