001/* 002 * Copyright (C) 2008 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.collect.testing.testers; 018 019import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES; 020 021import com.google.common.annotations.GwtCompatible; 022import com.google.common.annotations.GwtIncompatible; 023import com.google.common.collect.testing.Helpers; 024import com.google.common.collect.testing.features.CollectionFeature; 025import com.google.common.collect.testing.features.CollectionSize; 026import java.lang.reflect.Method; 027import java.util.Collection; 028 029/** 030 * Tests {@link java.util.Set#hashCode}. 031 * 032 * @author George van den Driessche 033 */ 034@GwtCompatible(emulated = true) 035public class SetHashCodeTester<E> extends AbstractSetTester<E> { 036 public void testHashCode() { 037 int expectedHashCode = 0; 038 for (E element : getSampleElements()) { 039 expectedHashCode += ((element == null) ? 0 : element.hashCode()); 040 } 041 assertEquals( 042 "A Set's hashCode() should be the sum of those of its elements.", 043 expectedHashCode, 044 getSet().hashCode()); 045 } 046 047 @CollectionSize.Require(absent = CollectionSize.ZERO) 048 @CollectionFeature.Require(ALLOWS_NULL_VALUES) 049 public void testHashCode_containingNull() { 050 Collection<E> elements = getSampleElements(getNumElements() - 1); 051 int expectedHashCode = 0; 052 for (E element : elements) { 053 expectedHashCode += ((element == null) ? 0 : element.hashCode()); 054 } 055 056 elements.add(null); 057 collection = getSubjectGenerator().create(elements.toArray()); 058 assertEquals( 059 "A Set's hashCode() should be the sum of those of its elements (with " 060 + "a null element counting as having a hash of zero).", 061 expectedHashCode, 062 getSet().hashCode()); 063 } 064 065 /** 066 * Returns the {@link Method} instances for the test methods in this class which call {@code 067 * hashCode()} on the set values so that set tests on unhashable objects can suppress it with 068 * {@code FeatureSpecificTestSuiteBuilder.suppressing()}. 069 */ 070 @GwtIncompatible // reflection 071 public static Method[] getHashCodeMethods() { 072 return new Method[] { 073 Helpers.getMethod(SetHashCodeTester.class, "testHashCode"), 074 Helpers.getMethod(SetHashCodeTester.class, "testHashCode_containingNull") 075 }; 076 } 077}