• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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.collect.testing.testers;
18 
19 import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
20 
21 import com.google.common.collect.testing.features.CollectionFeature;
22 import com.google.common.collect.testing.features.CollectionSize;
23 
24 import java.lang.reflect.Method;
25 import java.util.Collection;
26 
27 /**
28  * Tests {@link java.util.Set#hashCode}.
29  *
30  * <p>This class is GWT compatible.
31  *
32  * @author George van den Driessche
33  */
34 public class SetHashCodeTester<E> extends AbstractSetTester<E> {
testHashCode()35   public void testHashCode() {
36     int expectedHashCode = 0;
37     for (E element : getSampleElements()) {
38       expectedHashCode += ((element == null) ? 0 : element.hashCode());
39     }
40     assertEquals(
41         "A Set's hashCode() should be the sum of those of its elements.",
42         expectedHashCode, getSet().hashCode());
43   }
44 
45   @CollectionSize.Require(absent = CollectionSize.ZERO)
46   @CollectionFeature.Require(ALLOWS_NULL_VALUES)
testHashCode_containingNull()47   public void testHashCode_containingNull() {
48     Collection<E> elements = getSampleElements(getNumElements() - 1);
49     int expectedHashCode = 0;
50     for (E element : elements) {
51       expectedHashCode += ((element == null) ? 0 : element.hashCode());
52     }
53 
54     elements.add(null);
55     collection = getSubjectGenerator().create(elements.toArray());
56     assertEquals(
57         "A Set's hashCode() should be the sum of those of its elements (with "
58             + "a null element counting as having a hash of zero).",
59         expectedHashCode, getSet().hashCode());
60   }
61 
62   /**
63    * Returns the {@link Method} instances for the test methods in this class
64    * which call {@code hashCode()} on the set values so that set tests on
65    * unhashable objects can suppress it with
66    * {@code FeatureSpecificTestSuiteBuilder.suppressing()}.
67    */
getHashCodeMethods()68   public static Method[] getHashCodeMethods() {
69     return new Method[]{
70         Platform.getMethod(SetHashCodeTester.class, "testHashCode"),
71         Platform.getMethod(SetHashCodeTester.class, "testHashCode_containingNull") };
72   }
73 }
74