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