nl.jqno.equalsverifier
Class EqualsVerifier<T>

java.lang.Object
  extended by nl.jqno.equalsverifier.EqualsVerifier<T>
Type Parameters:
T - The class under test.

public final class EqualsVerifier<T>
extends Object

EqualsVerifier can be used in unit tests to verify whether the contract for the equals and hashCode methods in a class is met. The contracts are described in the Javadoc comments for the Object class.

Use, within unit test method, as follows:
- Create an instance of EqualsVerifier. Either call forExamples(Object, Object, Object...) to supply at least two instances of the class under test that are not equal to one another, or call forClass(Class) to supply a reference to the class itself to let the EqualsVerifier instantiate objects. Also, forRelaxedEqualExamples(Object, Object, Object...) can be used if the class under test has relaxed equality rules, for example, if the contents of two fields of the same type can be interchanged without breaking equality.
- If the class under test is designed for inheritance, and the equals and hashCode methods can be overridden, an instance of the class is not permitted to be equal to an instance of a subclass, even though all the relevant fields are equal. Call withRedefinedSubclass(Class) to supply a reference to such a subclass, or call suppress(Warning...) with Warning.STRICT_INHERITANCE to disable the check.
- Call suppress(Warning...) to suppress warnings given by EqualsVerifier.
- Call verify() to perform the actual verifications.

Example use:

EqualsVerifier.forClass(My.class).verify();
 
Or, if you prefer to use a getClass() check instead of an instanceof check in the body of your equals method:
EqualsVerifier.forClass(My.class)
     .usingGetClass()
     .verify();
 
With some warnings suppressed:
EqualsVerifier.forClass(My.class)
     .suppress(Warning.NONFINAL_FIELDS, Warning.NULL_FIELDS)
     .verify();
 
The following properties are verified:
- Preconditions for EqualsVerifier itself.
- Reflexivity and symmetry of the equals method.
- Symmetry and transitivity of the equals method within an inheritance hierarchy, when applicable.
- Consistency (by repeatedly calling equals).
- "Non-nullity".
- That equals, hashCode and toString not be able to throw NullPointerException. (Optional)
- The hashCode contract.
- That equals and hashCode be defined in terms of the same fields.
- The finality of the fields in terms of which equals and hashCode are defined. (Optional)
- The finality of the class under test and of the equals method itself, when applicable.
- That transient fields not be included in the equals contract for the class. (Optional)

For more information, see the documentation at http://www.jqno.nl/equalsverifier/

Author:
Jan Ouwens
See Also:
Object.equals(Object), Object.hashCode()

Nested Class Summary
static class EqualsVerifier.RelaxedEqualsVerifierHelper<T>
          Helper class for forRelaxedEqualExamples(Object, Object, Object...).
 
Method Summary
 EqualsVerifier<T> allFieldsShouldBeUsed()
          Signals that all non-transient fields are relevant in the equals contract.
 EqualsVerifier<T> allFieldsShouldBeUsedExcept(String... fields)
          Signals that all non-transient fields are relevant in the equals contract, except for the ones specified.
 EqualsVerifier<T> debug()
          Deprecated. No longer needed. The stack trace that this method printed, is now included as the cause of the AssertionError.
static
<T> EqualsVerifier<T>
forClass(Class<T> type)
          Factory method.
static
<T> EqualsVerifier<T>
forExamples(T first, T second, T... more)
          Factory method.
static
<T> EqualsVerifier.RelaxedEqualsVerifierHelper<T>
forRelaxedEqualExamples(T first, T second, T... more)
          Factory method.
 EqualsVerifier<T> suppress(Warning... warnings)
          Suppresses warnings given by EqualsVerifier.
 EqualsVerifier<T> usingGetClass()
          Signals that getClass is used in the implementation of the equals method, instead of an instanceof check.
 void verify()
          Performs the verification of the contracts for equals and hashCode.
 EqualsVerifier<T> withCachedHashCode(String cachedHashCodeField, String calculateHashCodeMethod, T example)
          Signals that T caches its hashCode, instead of re-calculating it each time the hashCode() method is called.
<S> EqualsVerifier<T>
withPrefabValues(Class<S> otherType, S red, S black)
          Adds prefabricated values for instance fields of classes that EqualsVerifier cannot instantiate by itself.
 EqualsVerifier<T> withRedefinedSubclass(Class<? extends T> redefinedSubclass)
          Supplies a reference to a subclass of T in which equals is overridden.
 EqualsVerifier<T> withRedefinedSuperclass()
          Signals that T is part of an inheritance hierarchy where equals is overridden.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

forClass

public static <T> EqualsVerifier<T> forClass(Class<T> type)
Factory method. For general use.

Parameters:
type - The class for which the equals method should be tested.

forExamples

public static <T> EqualsVerifier<T> forExamples(T first,
                                                T second,
                                                T... more)
Factory method. Use when it is necessary or desired to give explicit examples of instances of T. It's theoretically possible that forClass(Class) doesn't generate the examples that expose a certain weakness in the equals implementation. In such cases, this method can be used.

Parameters:
first - An instance of T.
second - Another instance of T, which is unequal to first.
more - More instances of T, all of which are unequal to one another and to first and second. May also contain instances of subclasses of T.

forRelaxedEqualExamples

public static <T> EqualsVerifier.RelaxedEqualsVerifierHelper<T> forRelaxedEqualExamples(T first,
                                                                                        T second,
                                                                                        T... more)
Factory method. Asks for a list of equal, but not identical, instances of T. For use when T is a class which has relaxed equality rules. This happens when two instances of T are equal even though the its internal state is different. This could happen, for example, in a Rational class that doesn't normalize: new Rational(1, 2).equals(new Rational(2, 4)) would return true. Using this factory method requires that EqualsVerifier.RelaxedEqualsVerifierHelper.andUnequalExamples(Object, Object...) be called to supply a list of unequal instances of T.

Parameters:
first - An instance of T.
second - Another instance of T, which is equal, but not identical, to first.
more - More instances of T, all of which are equal, but not identical, to one another and to first and second.

suppress

public EqualsVerifier<T> suppress(Warning... warnings)
Suppresses warnings given by EqualsVerifier. See Warning to see what warnings can be suppressed.

Parameters:
warnings - A list of warnings to suppress in EqualsVerifier.
Returns:
this, for easy method chaining.

withPrefabValues

public <S> EqualsVerifier<T> withPrefabValues(Class<S> otherType,
                                              S red,
                                              S black)
Adds prefabricated values for instance fields of classes that EqualsVerifier cannot instantiate by itself.

Type Parameters:
S - The class of the prefabricated values.
Parameters:
otherType - The class of the prefabricated values.
red - An instance of S.
black - Another instance of S.
Returns:
this, for easy method chaining.
Throws:
NullPointerException - If either otherType, red or black is null.
IllegalArgumentException - If red equals black.

usingGetClass

public EqualsVerifier<T> usingGetClass()
Signals that getClass is used in the implementation of the equals method, instead of an instanceof check.

Returns:
this, for easy method chaining.

allFieldsShouldBeUsed

public EqualsVerifier<T> allFieldsShouldBeUsed()
Signals that all non-transient fields are relevant in the equals contract. EqualsVerifier will fail if one non-transient field does not affect the outcome of equals.

Returns:
this, for easy method chaining.

allFieldsShouldBeUsedExcept

public EqualsVerifier<T> allFieldsShouldBeUsedExcept(String... fields)
Signals that all non-transient fields are relevant in the equals contract, except for the ones specified. EqualsVerifier will fail if one non-specified, non-transient field does not affect the outcome of equals, or if one specified field does.

Parameters:
fields -
Returns:
this, for easy method chaining.

withRedefinedSuperclass

public EqualsVerifier<T> withRedefinedSuperclass()
Signals that T is part of an inheritance hierarchy where equals is overridden. Call this method if T has overridden equals and hashCode, and one or more of T's superclasses have as well.

T itself does not necessarily have to have subclasses that redefine equals and hashCode.

Returns:
this, for easy method chaining.

withRedefinedSubclass

public EqualsVerifier<T> withRedefinedSubclass(Class<? extends T> redefinedSubclass)
Supplies a reference to a subclass of T in which equals is overridden. Calling this method is mandatory if equals is not final and a strong verification is performed. Note that, for each subclass that overrides equals, EqualsVerifier should be used as well to verify its adherence to the contracts.

Parameters:
redefinedSubclass - A subclass of T for which no instance can be equal to any instance of T.
Returns:
this, for easy method chaining.
See Also:
Warning.STRICT_INHERITANCE

withCachedHashCode

public EqualsVerifier<T> withCachedHashCode(String cachedHashCodeField,
                                            String calculateHashCodeMethod,
                                            T example)
Signals that T caches its hashCode, instead of re-calculating it each time the hashCode() method is called. There are 3 conditions to verify cached hashCodes: First, the class under test must have a private int field that contains the cached hashCode. Second, the class under test must have a private method that calculates the hashCode. The method must return an int and may not take any parameters. It should be used by the constructor or the hashCode method of the class under test to initialize the cached hashCode. This may lead to slightly awkward production code, but unfortunately, it is necessary for EqualsVerifier to verify that the hashCode is correct. Finally, only immutable objects can be verified. In other words, withCachedHashCode can not be used when Warning.NONFINAL_FIELDS is suppressed.

Parameters:
cachedHashCodeField - The name of the field which stores the cached hash code.
calculateHashCodeMethod - The name of the method which recomputes the hash code. It should return an int and take no parameters.
example - An instance of the class under test, to verify that the hashCode has been initialized properly.
Returns:
this, for easy method chaining.

debug

@Deprecated
public EqualsVerifier<T> debug()
Deprecated. No longer needed. The stack trace that this method printed, is now included as the cause of the AssertionError.

Returns:
this, for easy method chaining.

verify

public void verify()
Performs the verification of the contracts for equals and hashCode.

Throws:
AssertionError - If the contract is not met, or if EqualsVerifier's preconditions do not hold.


Copyright © 2015. All Rights Reserved.