liveBook · Manning

EqualsVerifier

As explained in 100 Java Mistakes and How to Avoid Them

EqualsVerifier is a Java library that tests whether equals and hashCode implementations comply with their contracts.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Checks equality implementations broadly for listed contract problems but does not describe its internal verification algorithm.
Examples
Uses malformed MyEntity and User implementations plus assertNotEquals() tests that fail to exercise the intended equals() method.
What you can do after
Diagnose equality-contract defects with EqualsVerifier instead of relying solely on manually designed assertions.
How it connects
Links equals() and hashCode() with equality contracts, unit testing, Objects.equals(), IDE generation, and record classes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.