Tester for equals() and hashCode() methods of a class.
To use, create a new EqualsTester and add equality groups where each group contains objects that are supposed to be equal to each other, and objects of different groups are expected to be unequal. For example:
new EqualsTester() .addEqualityGroup("hello", "h" + "ello") .addEqualityGroup("world", "wor" + "ld") .addEqualityGroup(2, 1 + 1) .testEquals();
This tests:
- comparing each object against itself returns true
- comparing each object against null returns false
- comparing each object an instance of an incompatible class returns false
- comparing each pair of objects within the same equality group returns true
- comparing each pair of objects from different equality groups returns false
- the hash code of any two equal objects are equal
For backward compatibility, the following usage pattern is also supported:
- Create a reference instance of the class under test and use to create a new EqualsTester.
- Create one or more new instances of the class that should be equal to the reference instance and pass to addEqualObject(). Multiple instances can be used to test subclasses.
- Invoke {@link #testEquals} on the EqualsTester.
When a test fails, the error message labels the objects involved in the failed comparison as follows:
- {@link #addEqualObject(Object)}, numbered starting from 1.
- " {@code [group }i {@code , item }j {@code ]}" refers to the jth item in the ith equality group, where both equality groups and the items within equality groups are numbered starting from 1. When either a constructor argument or an equal object is provided, that becomes group 1.
@author Jim McMaster
@author Jige Yu
@since Guava release 10