001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.testing;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020import static junit.framework.Assert.assertEquals;
021import static junit.framework.Assert.assertTrue;
022
023import com.google.common.annotations.Beta;
024import com.google.common.annotations.GwtCompatible;
025import com.google.common.base.Equivalence;
026import com.google.common.collect.ImmutableList;
027import com.google.common.collect.Iterables;
028import com.google.common.collect.Lists;
029import java.util.List;
030
031/**
032 * Tester for equals() and hashCode() methods of a class.
033 *
034 * <p>The simplest use case is:
035 *
036 * <pre>
037 * new EqualsTester().addEqualityGroup(foo).testEquals();
038 * </pre>
039 *
040 * <p>This tests {@code foo.equals(foo)}, {@code foo.equals(null)}, and a few other operations.
041 *
042 * <p>For more extensive testing, add multiple equality groups. Each group should contain objects
043 * that are equal to each other but unequal to the objects in any other group. For example:
044 *
045 * <pre>
046 * new EqualsTester()
047 *     .addEqualityGroup(new User("page"), new User("page"))
048 *     .addEqualityGroup(new User("sergey"))
049 *     .testEquals();
050 * </pre>
051 *
052 * <p>This tests:
053 *
054 * <ul>
055 *   <li>comparing each object against itself returns true
056 *   <li>comparing each object against null returns false
057 *   <li>comparing each object against an instance of an incompatible class returns false
058 *   <li>comparing each pair of objects within the same equality group returns true
059 *   <li>comparing each pair of objects from different equality groups returns false
060 *   <li>the hash codes of any two equal objects are equal
061 * </ul>
062 *
063 * <p>When a test fails, the error message labels the objects involved in the failed comparison as
064 * follows:
065 *
066 * <ul>
067 *   <li>"{@code [group }<i>i</i>{@code , item }<i>j</i>{@code ]}" refers to the
068 *       <i>j</i><sup>th</sup> item in the <i>i</i><sup>th</sup> equality group, where both equality
069 *       groups and the items within equality groups are numbered starting from 1. When either a
070 *       constructor argument or an equal object is provided, that becomes group 1.
071 * </ul>
072 *
073 * @author Jim McMaster
074 * @author Jige Yu
075 * @since 10.0
076 */
077@Beta
078@GwtCompatible
079public final class EqualsTester {
080  private static final int REPETITIONS = 3;
081
082  private final List<List<Object>> equalityGroups = Lists.newArrayList();
083  private final RelationshipTester.ItemReporter itemReporter;
084
085  /** Constructs an empty EqualsTester instance */
086  public EqualsTester() {
087    this(new RelationshipTester.ItemReporter());
088  }
089
090  EqualsTester(RelationshipTester.ItemReporter itemReporter) {
091    this.itemReporter = checkNotNull(itemReporter);
092  }
093
094  /**
095   * Adds {@code equalityGroup} with objects that are supposed to be equal to each other and not
096   * equal to any other equality groups added to this tester.
097   */
098  public EqualsTester addEqualityGroup(Object... equalityGroup) {
099    checkNotNull(equalityGroup);
100    equalityGroups.add(ImmutableList.copyOf(equalityGroup));
101    return this;
102  }
103
104  /** Run tests on equals method, throwing a failure on an invalid test */
105  public EqualsTester testEquals() {
106    RelationshipTester<Object> delegate =
107        new RelationshipTester<>(
108            Equivalence.equals(), "Object#equals", "Object#hashCode", itemReporter);
109    for (List<Object> group : equalityGroups) {
110      delegate.addRelatedGroup(group);
111    }
112    for (int run = 0; run < REPETITIONS; run++) {
113      testItems();
114      delegate.test();
115    }
116    return this;
117  }
118
119  private void testItems() {
120    for (Object item : Iterables.concat(equalityGroups)) {
121      assertTrue(item + " must not be Object#equals to null", !item.equals(null));
122      assertTrue(
123          item + " must not be Object#equals to an arbitrary object of another class",
124          !item.equals(NotAnInstance.EQUAL_TO_NOTHING));
125      assertEquals(item + " must be Object#equals to itself", item, item);
126      assertEquals(
127          "the Object#hashCode of " + item + " must be consistent",
128          item.hashCode(),
129          item.hashCode());
130      if (!(item instanceof String)) {
131        assertTrue(
132            item + " must not be Object#equals to its Object#toString representation",
133            !item.equals(item.toString()));
134      }
135    }
136  }
137
138  /**
139   * Class used to test whether equals() correctly handles an instance of an incompatible class.
140   * Since it is a private inner class, the invoker can never pass in an instance to the tester
141   */
142  private enum NotAnInstance {
143    EQUAL_TO_NOTHING;
144  }
145}