Sub topic 15
Testing the contracts
The equals and hashCode contracts are easy to break without noticing. A broken class compiles, passes a quick manual check, and then misbehaves later inside a HashMap. This chapter shows how to write tests that catch those breaks.
This chapter assumes you have read the chapters on the equals contract, the hashCode contract, and how hash collections use both. You also need basic JUnit 5 experience (@Test and the Assertions methods).
What a test must cover
Each rule in the contracts becomes at least one assertion. The table lists them.
| Rule | What to assert |
|---|---|
| Reflexive | `a.equals(a)` is true |
| Symmetric | `a.equals(b)` and `b.equals(a)` give the same result |
| Transitive | If `a` equals `b` and `b` equals `c`, then `a` equals `c` |
| Consistent | Repeated calls on unchanged objects give the same result |
| Null | `a.equals(null)` is false and does not throw |
| Different type | `a.equals(new Object())` is false and does not throw |
| `hashCode` agrees | Equal objects have equal hash codes |
| `hashCode` stable | Repeated calls on an unchanged object return the same value |
| Field sensitivity | Changing any single field that participates in equality makes the objects unequal |
The last row is not part of the contract. It catches a common bug, which is forgetting a field. A class whose equals always returns true for the same type still satisfies every other row.
Call equals directly
Prefer assertTrue(a.equals(b)) over assertEquals(a, b). JUnit's assertEquals calls equals for you, but it also special-cases nulls and hides which object is the receiver. When you test symmetry, you need to control the direction of each call. Writing a.equals(b) and b.equals(a) explicitly keeps the test honest.
A reusable contract checker
You will repeat the same checks for every value class, so put them in one helper. The helper takes three distinct instances that you claim are all equal. These tests use the Point class from the chapter on writing equals step by step.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
final class ContractAssertions {
private ContractAssertions() {}
/** a, b and c must be three distinct instances that are all logically equal. */
static <T> void assertEqualsContract(T a, T b, T c) {
assertNotSame(a, b);
assertNotSame(b, c);
// reflexive
assertTrue(a.equals(a));
// symmetric
assertTrue(a.equals(b));
assertTrue(b.equals(a));
// transitive
assertTrue(b.equals(c));
assertTrue(a.equals(c));
// null and foreign types
assertFalse(a.equals(null));
assertFalse(a.equals(new Object()));
// consistent
for (int i = 0; i < 3; i++) {
assertTrue(a.equals(b));
}
// hashCode agrees with equals and is stable
assertEquals(a.hashCode(), b.hashCode());
assertEquals(b.hashCode(), c.hashCode());
assertEquals(a.hashCode(), a.hashCode());
}
/** Equal-ness must fail in both directions. */
static <T> void assertNotEqual(T a, T b) {
assertFalse(a.equals(b));
assertFalse(b.equals(a));
}
}The assertNotSame calls guard against a lazy test. If you passed the same object three times, equals would pass through its this == o shortcut and the real comparison code would never run.
Testing a concrete class
With the helper in place, a test class for Point is short.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class PointTest {
@Test
void satisfiesEqualsAndHashCodeContracts() {
ContractAssertions.assertEqualsContract(
new Point(1, 2), new Point(1, 2), new Point(1, 2));
}
@Test
void everyFieldMatters() {
Point base = new Point(1, 2);
ContractAssertions.assertNotEqual(base, new Point(9, 2));
ContractAssertions.assertNotEqual(base, new Point(1, 9));
}
@Test
void worksInHashSet() {
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
assertTrue(set.contains(new Point(1, 2)));
assertFalse(set.contains(new Point(2, 1)));
set.add(new Point(1, 2));
assertEquals(1, set.size());
}
@Test
void toStringShowsFields() {
assertEquals("Point{x=1, y=2}", new Point(1, 2).toString());
}
}The worksInHashSet test is the most valuable one. It exercises the same path as production code: hashCode picks a bucket, then equals confirms a match. If you forgot hashCode, this test fails even when direct equals calls succeed. The tag example from the chapter on hash collections would fail it.
Why the field-sensitivity test uses one change at a time
If you changed both fields at once, a equals that only compared x would still report the objects as unequal. Changing a single field per assertion pinpoints which field the implementation ignores.
Add a pair of unequal objects for every field that should count, and add one more case for objects that differ only in a nullable field or in array contents if the class has them.
Writing a test that fails on purpose
A test for symmetry in a class hierarchy should fail when the hierarchy is broken. The Pt and ColorPt classes from the chapter on inheritance pitfalls are such a case. They need to be in the same package as the test.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class PtSymmetryTest {
@Test
void equalsIsSymmetricAcrossSubclass() {
Pt p = new Pt(1, 2);
ColorPt cp = new ColorPt(1, 2, "red");
assertEquals(p.equals(cp), cp.equals(p));
}
}With the earlier ColorPt implementation, this test fails: p.equals(cp) is true and cp.equals(p) is false. A failing test is the right result here. It proves the check can detect the bug. After you fix the hierarchy (for example with composition instead of inheritance), the same test should pass.
Testing hashCode stability for mutable classes
The contract says hashCode must stay the same while the fields used in equals do not change. A class with mutable fields can still satisfy this, but a hash-based collection will lose the object once a field changes. Test the behavior you promise to callers.
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class MutableKeyTest {
@Test
void hashCodeChangesWhenContentChanges() {
List<Integer> key = new ArrayList<>(List.of(1));
int before = key.hashCode();
key.add(2);
assertNotEquals(before, key.hashCode());
}
}This test documents why such an object must not be used as a key after mutation. If your own class is meant to be a key, the better test is that its fields are final and that defensive copies are made, as the Sample class does with values.clone().
Using a library: EqualsVerifier
Handwritten checks cover the cases you thought of. EqualsVerifier is a test library that generates instances through reflection and probes many more cases. These include forgotten fields, missing null handling, and subclass symmetry problems. Add it as a test-scope dependency (nl.jqno.equalsverifier:equalsverifier).
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
class PointVerifierTest {
@Test
void equalsAndHashCodeAreCorrect() {
EqualsVerifier.forClass(Point.class).verify();
}
}The library is strict by design. It reports problems such as non-final fields and classes that are not final, and you silence a warning with an explicit .suppress(...) call. Silencing should be a conscious decision, not a reflex.
Testing records and generated methods
Records generate equals, hashCode, and toString, so you do not need to test the contract itself. The compiler guarantees it. Test only what you add yourself:
- A compact constructor that validates or copies arguments.
- An overridden
equalsortoString, if you wrote one. - Components that are arrays. A record compares array components by reference, so two records holding equal arrays are not equal.
Common mistakes in contract tests
- Passing the same instance twice, so the real comparison logic is never reached.
- Testing only
a.equals(b)and neverb.equals(a). - Checking
equalsbut nothashCode, or the reverse. - Asserting the exact
toStringtext of a class whose format is not documented. Such a test breaks on harmless changes. Assert exact text only for a format you promise, and otherwise usecontainsfor the field values. - Comparing hash codes of unequal objects with
assertNotEquals. Collisions are legal, so this test can fail for correct code. The contract only requires that equal objects share a hash code.
Exercise
A teammate writes assertEquals(a, b) and assertEquals(a.hashCode(), b.hashCode()) and says the symmetry rule is tested. What is missing, and which additional single assertion fixes it?
Show answer
assertEquals(a, b) only calls a.equals(b), so the direction b.equals(a) is never tested. Add assertTrue(b.equals(a)). Symmetry holds only if both directions return the same result.
Exercise
A class overrides equals but forgets hashCode. Its direct equals tests all pass. Which test from this chapter would fail, and why?
Show answer
The test that uses the object in a HashSet (or HashMap), and the assertEquals(a.hashCode(), b.hashCode()) check in the helper. Two equal objects get different identity-based hash codes, so the set looks in the wrong bucket and contains returns false.