• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.testing;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 import static junit.framework.Assert.assertEquals;
21 import static junit.framework.Assert.assertTrue;
22 
23 import com.google.common.annotations.GwtCompatible;
24 import com.google.common.base.Equivalence;
25 import com.google.common.collect.Iterables;
26 import com.google.common.collect.Lists;
27 import com.google.errorprone.annotations.CanIgnoreReturnValue;
28 import java.util.ArrayList;
29 import java.util.List;
30 import org.checkerframework.checker.nullness.qual.Nullable;
31 
32 /**
33  * Tester for equals() and hashCode() methods of a class.
34  *
35  * <p>The simplest use case is:
36  *
37  * <pre>
38  * new EqualsTester().addEqualityGroup(foo).testEquals();
39  * </pre>
40  *
41  * <p>This tests {@code foo.equals(foo)}, {@code foo.equals(null)}, and a few other operations.
42  *
43  * <p>For more extensive testing, add multiple equality groups. Each group should contain objects
44  * that are equal to each other but unequal to the objects in any other group. For example:
45  *
46  * <pre>
47  * new EqualsTester()
48  *     .addEqualityGroup(new User("page"), new User("page"))
49  *     .addEqualityGroup(new User("sergey"))
50  *     .testEquals();
51  * </pre>
52  *
53  * <p>This tests:
54  *
55  * <ul>
56  *   <li>comparing each object against itself returns true
57  *   <li>comparing each object against null returns false
58  *   <li>comparing each object against an instance of an incompatible class returns false
59  *   <li>comparing each pair of objects within the same equality group returns true
60  *   <li>comparing each pair of objects from different equality groups returns false
61  *   <li>the hash codes of any two equal objects are equal
62  * </ul>
63  *
64  * <p>When a test fails, the error message labels the objects involved in the failed comparison as
65  * follows:
66  *
67  * <ul>
68  *   <li>"{@code [group }<i>i</i>{@code , item }<i>j</i>{@code ]}" refers to the
69  *       <i>j</i><sup>th</sup> item in the <i>i</i><sup>th</sup> equality group, where both equality
70  *       groups and the items within equality groups are numbered starting from 1. When either a
71  *       constructor argument or an equal object is provided, that becomes group 1.
72  * </ul>
73  *
74  * @author Jim McMaster
75  * @author Jige Yu
76  * @since 10.0
77  */
78 @GwtCompatible
79 @ElementTypesAreNonnullByDefault
80 public final class EqualsTester {
81   private static final int REPETITIONS = 3;
82 
83   private final List<List<Object>> equalityGroups = Lists.newArrayList();
84   private final RelationshipTester.ItemReporter itemReporter;
85 
86   /** Constructs an empty EqualsTester instance */
EqualsTester()87   public EqualsTester() {
88     this(new RelationshipTester.ItemReporter());
89   }
90 
EqualsTester(RelationshipTester.ItemReporter itemReporter)91   EqualsTester(RelationshipTester.ItemReporter itemReporter) {
92     this.itemReporter = checkNotNull(itemReporter);
93   }
94 
95   /**
96    * Adds {@code equalityGroup} with objects that are supposed to be equal to each other and not
97    * equal to any other equality groups added to this tester.
98    *
99    * <p>The {@code @Nullable} annotations on the {@code equalityGroup} parameter imply that the
100    * objects, and the array itself, can be null. That is for programmer convenience, when the
101    * objects come from factory methods that are themselves {@code @Nullable}. In reality neither the
102    * array nor its contents can be null, but it is not useful to force the use of {@code
103    * requireNonNull} or the like just to assert that.
104    *
105    * <p>{@code EqualsTester} will always check that every object it is given returns false from
106    * {@code equals(null)}, so it is neither useful nor allowed to include a null value in any
107    * equality group.
108    */
109   @CanIgnoreReturnValue
addEqualityGroup(@ullable Object @ullable .... equalityGroup)110   public EqualsTester addEqualityGroup(@Nullable Object @Nullable ... equalityGroup) {
111     checkNotNull(equalityGroup);
112     List<Object> list = new ArrayList<>(equalityGroup.length);
113     for (int i = 0; i < equalityGroup.length; i++) {
114       Object element = equalityGroup[i];
115       if (element == null) {
116         throw new NullPointerException("at index " + i);
117       }
118       list.add(element);
119     }
120     equalityGroups.add(list);
121     return this;
122   }
123 
124   /** Run tests on equals method, throwing a failure on an invalid test */
125   @CanIgnoreReturnValue
testEquals()126   public EqualsTester testEquals() {
127     RelationshipTester<Object> delegate =
128         new RelationshipTester<>(
129             Equivalence.equals(), "Object#equals", "Object#hashCode", itemReporter);
130     for (List<Object> group : equalityGroups) {
131       delegate.addRelatedGroup(group);
132     }
133     for (int run = 0; run < REPETITIONS; run++) {
134       testItems();
135       delegate.test();
136     }
137     return this;
138   }
139 
testItems()140   private void testItems() {
141     for (Object item : Iterables.concat(equalityGroups)) {
142       assertTrue(item + " must not be Object#equals to null", !item.equals(null));
143       assertTrue(
144           item + " must not be Object#equals to an arbitrary object of another class",
145           !item.equals(NotAnInstance.EQUAL_TO_NOTHING));
146       assertTrue(item + " must be Object#equals to itself", item.equals(item));
147       assertEquals(
148           "the Object#hashCode of " + item + " must be consistent",
149           item.hashCode(),
150           item.hashCode());
151       if (!(item instanceof String)) {
152         assertTrue(
153             item + " must not be Object#equals to its Object#toString representation",
154             !item.equals(item.toString()));
155       }
156     }
157   }
158 
159   /**
160    * Class used to test whether equals() correctly handles an instance of an incompatible class.
161    * Since it is a private inner class, the invoker can never pass in an instance to the tester
162    */
163   private enum NotAnInstance {
164     EQUAL_TO_NOTHING;
165   }
166 }
167