diff options
Diffstat (limited to 'android/guava-testlib')
20 files changed, 135 insertions, 2977 deletions
diff --git a/android/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java b/android/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java index b4e5b35e8..f26e6826b 100644 --- a/android/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java +++ b/android/guava-testlib/src/com/google/common/collect/testing/AbstractIteratorTester.java @@ -58,7 +58,7 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> { static final PermittedMetaException UOE_OR_ISE = new PermittedMetaException("UnsupportedOperationException or IllegalStateException") { @Override - boolean isPermitted(RuntimeException exception) { + boolean isPermitted(Exception exception) { return exception instanceof UnsupportedOperationException || exception instanceof IllegalStateException; } @@ -66,21 +66,21 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> { static final PermittedMetaException UOE = new PermittedMetaException("UnsupportedOperationException") { @Override - boolean isPermitted(RuntimeException exception) { + boolean isPermitted(Exception exception) { return exception instanceof UnsupportedOperationException; } }; static final PermittedMetaException ISE = new PermittedMetaException("IllegalStateException") { @Override - boolean isPermitted(RuntimeException exception) { + boolean isPermitted(Exception exception) { return exception instanceof IllegalStateException; } }; static final PermittedMetaException NSEE = new PermittedMetaException("NoSuchElementException") { @Override - boolean isPermitted(RuntimeException exception) { + boolean isPermitted(Exception exception) { return exception instanceof NoSuchElementException; } }; @@ -89,9 +89,9 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> { super(message); } - abstract boolean isPermitted(RuntimeException exception); + abstract boolean isPermitted(Exception exception); - void assertPermitted(RuntimeException exception) { + void assertPermitted(Exception exception) { if (!isPermitted(exception)) { String message = "Exception " @@ -313,10 +313,11 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> { protected void verify(List<E> elements) {} /** Executes the test. */ + @SuppressWarnings("CatchingUnchecked") // sneaky checked exception public final void test() { try { recurse(0); - } catch (RuntimeException e) { + } catch (Exception e) { // sneaky checked exception throw new RuntimeException(Arrays.toString(stimuli), e); } } @@ -372,16 +373,17 @@ abstract class AbstractIteratorTester<E, I extends Iterator<E>> { * * @see Stimulus#executeAndCompare(ListIterator, Iterator) */ + @SuppressWarnings("CatchingUnchecked") // sneaky checked exception private <T extends Iterator<E>> void internalExecuteAndCompare( T reference, T target, IteratorOperation method) { Object referenceReturnValue = null; PermittedMetaException referenceException = null; Object targetReturnValue = null; - RuntimeException targetException = null; + Exception targetException = null; try { targetReturnValue = method.execute(target); - } catch (RuntimeException e) { + } catch (Exception e) { // sneaky checked exception targetException = e; } diff --git a/android/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java b/android/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java index adbc8dcc6..cd9cbfdea 100644 --- a/android/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java +++ b/android/guava-testlib/src/com/google/common/collect/testing/AbstractTester.java @@ -17,6 +17,7 @@ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; +import com.google.common.annotations.GwtIncompatible; import junit.framework.TestCase; import org.checkerframework.checker.nullness.qual.Nullable; @@ -31,7 +32,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; * parameterize the test. * @author George van den Driessche */ -@GwtCompatible +@GwtCompatible(emulated = true) public class AbstractTester<G> extends TestCase { private G subjectGenerator; private String suiteName; @@ -73,10 +74,12 @@ public class AbstractTester<G> extends TestCase { } /** Returns the name of the test method invoked by this test instance. */ + @GwtIncompatible // not used under GWT, and super.getName() is not available under J2CL public final String getTestMethodName() { return super.getName(); } + @GwtIncompatible // not used under GWT, and super.getName() is not available under J2CL @Override public String getName() { return Platform.format("%s[%s]", super.getName(), suiteName); diff --git a/android/guava-testlib/src/com/google/common/collect/testing/IteratorFeature.java b/android/guava-testlib/src/com/google/common/collect/testing/IteratorFeature.java index c447e2922..c1e502272 100644 --- a/android/guava-testlib/src/com/google/common/collect/testing/IteratorFeature.java +++ b/android/guava-testlib/src/com/google/common/collect/testing/IteratorFeature.java @@ -16,10 +16,13 @@ package com.google.common.collect.testing; +import static java.util.Arrays.asList; +import static java.util.Collections.emptySet; +import static java.util.Collections.unmodifiableSet; + import com.google.common.annotations.GwtCompatible; -import java.util.Collections; -import java.util.EnumSet; import java.util.Iterator; +import java.util.LinkedHashSet; import java.util.ListIterator; import java.util.Set; @@ -49,12 +52,12 @@ public enum IteratorFeature { * A set containing none of the optional features of the {@link Iterator} or {@link ListIterator} * interfaces. */ - public static final Set<IteratorFeature> UNMODIFIABLE = Collections.emptySet(); + public static final Set<IteratorFeature> UNMODIFIABLE = emptySet(); /** * A set containing all of the optional features of the {@link Iterator} and {@link ListIterator} * interfaces. */ public static final Set<IteratorFeature> MODIFIABLE = - Collections.unmodifiableSet(EnumSet.allOf(IteratorFeature.class)); + unmodifiableSet(new LinkedHashSet<>(asList(values()))); } diff --git a/android/guava-testlib/src/com/google/common/collect/testing/MapInterfaceTest.java b/android/guava-testlib/src/com/google/common/collect/testing/MapInterfaceTest.java index 484913878..067973c2a 100644 --- a/android/guava-testlib/src/com/google/common/collect/testing/MapInterfaceTest.java +++ b/android/guava-testlib/src/com/google/common/collect/testing/MapInterfaceTest.java @@ -477,8 +477,8 @@ public abstract class MapInterfaceTest<K, V> extends TestCase { } catch (IllegalStateException expected) { } } else { + iterator.next(); try { - iterator.next(); iterator.remove(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException expected) { @@ -729,7 +729,7 @@ public abstract class MapInterfaceTest<K, V> extends TestCase { try { entrySet.retainAll(null); // Returning successfully is not ideal, but tolerated. - } catch (NullPointerException expected) { + } catch (NullPointerException tolerated) { } } else { try { @@ -1365,7 +1365,7 @@ public abstract class MapInterfaceTest<K, V> extends TestCase { try { keySet.retainAll(null); // Returning successfully is not ideal, but tolerated. - } catch (NullPointerException expected) { + } catch (NullPointerException tolerated) { } } else { try { @@ -1425,8 +1425,8 @@ public abstract class MapInterfaceTest<K, V> extends TestCase { } catch (IllegalStateException expected) { } } else { + iterator.next(); try { - iterator.next(); iterator.remove(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException expected) { @@ -1527,7 +1527,7 @@ public abstract class MapInterfaceTest<K, V> extends TestCase { try { values.removeAll(null); // Returning successfully is not ideal, but tolerated. - } catch (NullPointerException expected) { + } catch (NullPointerException tolerated) { } } else { try { @@ -1581,7 +1581,7 @@ public abstract class MapInterfaceTest<K, V> extends TestCase { try { values.retainAll(null); // Returning successfully is not ideal, but tolerated. - } catch (NullPointerException expected) { + } catch (NullPointerException tolerated) { } } else { try { diff --git a/android/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultisetSetCountTester.java b/android/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultisetSetCountTester.java index a72fd9fba..cd28cdc28 100644 --- a/android/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultisetSetCountTester.java +++ b/android/guava-testlib/src/com/google/common/collect/testing/google/AbstractMultisetSetCountTester.java @@ -188,9 +188,9 @@ public abstract class AbstractMultisetSetCountTester<E> extends AbstractMultiset @CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) public void testSetCountZeroToOneConcurrentWithIteration() { + Iterator<E> iterator = collection.iterator(); + assertSetCount(e3(), 1); try { - Iterator<E> iterator = collection.iterator(); - assertSetCount(e3(), 1); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { @@ -200,9 +200,9 @@ public abstract class AbstractMultisetSetCountTester<E> extends AbstractMultiset @CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) public void testSetCountZeroToOneConcurrentWithEntrySetIteration() { + Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator(); + assertSetCount(e3(), 1); try { - Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator(); - assertSetCount(e3(), 1); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { @@ -248,9 +248,9 @@ public abstract class AbstractMultisetSetCountTester<E> extends AbstractMultiset @CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(absent = ZERO) public void testSetCountOneToZeroConcurrentWithIteration() { + Iterator<E> iterator = collection.iterator(); + assertSetCount(e0(), 0); try { - Iterator<E> iterator = collection.iterator(); - assertSetCount(e0(), 0); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { @@ -261,9 +261,9 @@ public abstract class AbstractMultisetSetCountTester<E> extends AbstractMultiset @CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION}) @CollectionSize.Require(absent = ZERO) public void testSetCountOneToZeroConcurrentWithEntrySetIteration() { + Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator(); + assertSetCount(e0(), 0); try { - Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator(); - assertSetCount(e0(), 0); iterator.next(); fail("Expected ConcurrentModificationException"); } catch (ConcurrentModificationException expected) { diff --git a/android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableMapNavigationTester.java b/android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableMapNavigationTester.java index ebb86b615..936783e77 100644 --- a/android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableMapNavigationTester.java +++ b/android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableMapNavigationTester.java @@ -20,6 +20,7 @@ import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE; +import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractMapTester; @@ -162,11 +163,7 @@ public class NavigableMapNavigationTester<K, V> extends AbstractMapTester<K, V> @MapFeature.Require(absent = SUPPORTS_REMOVE) public void testPollFirstUnsupported() { - try { - navigableMap.pollFirstEntry(); - fail(); - } catch (UnsupportedOperationException e) { - } + assertThrows(UnsupportedOperationException.class, () -> navigableMap.pollFirstEntry()); } @CollectionSize.Require(SEVERAL) @@ -229,11 +226,7 @@ public class NavigableMapNavigationTester<K, V> extends AbstractMapTester<K, V> @MapFeature.Require(absent = SUPPORTS_REMOVE) @CollectionSize.Require(SEVERAL) public void testPollLastUnsupported() { - try { - navigableMap.pollLastEntry(); - fail(); - } catch (UnsupportedOperationException e) { - } + assertThrows(UnsupportedOperationException.class, () -> navigableMap.pollLastEntry()); } @CollectionSize.Require(SEVERAL) diff --git a/android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableSetNavigationTester.java b/android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableSetNavigationTester.java index 8b056b4cb..354dd608d 100644 --- a/android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableSetNavigationTester.java +++ b/android/guava-testlib/src/com/google/common/collect/testing/testers/NavigableSetNavigationTester.java @@ -20,6 +20,7 @@ import static com.google.common.collect.testing.features.CollectionFeature.SUPPO import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.SEVERAL; import static com.google.common.collect.testing.features.CollectionSize.ZERO; +import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.Helpers; @@ -128,11 +129,7 @@ public class NavigableSetNavigationTester<E> extends AbstractSetTester<E> { @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testPollFirstUnsupported() { - try { - navigableSet.pollFirst(); - fail(); - } catch (UnsupportedOperationException e) { - } + assertThrows(UnsupportedOperationException.class, () -> navigableSet.pollFirst()); } @CollectionSize.Require(SEVERAL) @@ -209,11 +206,7 @@ public class NavigableSetNavigationTester<E> extends AbstractSetTester<E> { @CollectionFeature.Require(absent = SUPPORTS_REMOVE) public void testPollLastUnsupported() { - try { - navigableSet.pollLast(); - fail(); - } catch (UnsupportedOperationException e) { - } + assertThrows(UnsupportedOperationException.class, () -> navigableSet.pollLast()); } @CollectionSize.Require(SEVERAL) diff --git a/android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java b/android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java index a52373d64..c47ea9113 100644 --- a/android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java +++ b/android/guava-testlib/src/com/google/common/testing/ArbitraryInstances.java @@ -17,6 +17,7 @@ package com.google.common.testing; import static com.google.common.base.Preconditions.checkArgument; +import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -410,7 +411,8 @@ public final class ArbitraryInstances { } private static <T> T createEmptyArray(Class<T> arrayType) { - return arrayType.cast(Array.newInstance(arrayType.getComponentType(), 0)); + // getComponentType() is non-null because we call createEmptyArray only with an array type. + return arrayType.cast(Array.newInstance(requireNonNull(arrayType.getComponentType()), 0)); } // Internal implementations of some classes, with public default constructor that get() needs. diff --git a/android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java b/android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java index 3a41a7fe1..2c80552ae 100644 --- a/android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java +++ b/android/guava-testlib/src/com/google/common/testing/ClassSanityTester.java @@ -496,13 +496,14 @@ public final class ClassSanityTester { * @return this tester */ @CanIgnoreReturnValue + @SuppressWarnings("CatchingUnchecked") // sneaky checked exception public FactoryMethodReturnValueTester testSerializable() throws Exception { for (Invokable<?, ?> factory : getFactoriesToTest()) { Object instance = instantiate(factory); if (instance != null) { try { SerializableTester.reserialize(instance); - } catch (RuntimeException e) { + } catch (Exception e) { // sneaky checked exception AssertionError error = new AssertionFailedError("Serialization failed on return value of " + factory); error.initCause(e.getCause()); @@ -522,6 +523,7 @@ public final class ClassSanityTester { * @return this tester */ @CanIgnoreReturnValue + @SuppressWarnings("CatchingUnchecked") // sneaky checked exception public FactoryMethodReturnValueTester testEqualsAndSerializable() throws Exception { for (Invokable<?, ?> factory : getFactoriesToTest()) { try { @@ -533,7 +535,7 @@ public final class ClassSanityTester { if (instance != null) { try { SerializableTester.reserializeAndAssert(instance); - } catch (RuntimeException e) { + } catch (Exception e) { // sneaky checked exception AssertionError error = new AssertionFailedError("Serialization failed on return value of " + factory); error.initCause(e.getCause()); diff --git a/android/guava-testlib/src/com/google/common/testing/EqualsTester.java b/android/guava-testlib/src/com/google/common/testing/EqualsTester.java index d4484702a..5f02dba84 100644 --- a/android/guava-testlib/src/com/google/common/testing/EqualsTester.java +++ b/android/guava-testlib/src/com/google/common/testing/EqualsTester.java @@ -95,6 +95,16 @@ public final class EqualsTester { /** * Adds {@code equalityGroup} with objects that are supposed to be equal to each other and not * equal to any other equality groups added to this tester. + * + * <p>The {@code @Nullable} annotations on the {@code equalityGroup} parameter imply that the + * objects, and the array itself, can be null. That is for programmer convenience, when the + * objects come from factory methods that are themselves {@code @Nullable}. In reality neither the + * array nor its contents can be null, but it is not useful to force the use of {@code + * requireNonNull} or the like just to assert that. + * + * <p>{@code EqualsTester} will always check that every object it is given returns false from + * {@code equals(null)}, so it is neither useful nor allowed to include a null value in any + * equality group. */ @CanIgnoreReturnValue public EqualsTester addEqualityGroup(@Nullable Object @Nullable ... equalityGroup) { diff --git a/android/guava-testlib/src/com/google/common/testing/NullPointerTester.java b/android/guava-testlib/src/com/google/common/testing/NullPointerTester.java index 73c5705ba..d0202b471 100644 --- a/android/guava-testlib/src/com/google/common/testing/NullPointerTester.java +++ b/android/guava-testlib/src/com/google/common/testing/NullPointerTester.java @@ -35,7 +35,6 @@ import com.google.common.reflect.Reflection; import com.google.common.reflect.TypeToken; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedType; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; @@ -43,7 +42,6 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; import java.util.Arrays; import java.util.List; import java.util.concurrent.ConcurrentMap; @@ -353,9 +351,9 @@ public final class NullPointerTester { @Nullable Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) { /* * com.google.common is starting to rely on type-use annotations, which aren't visible under - * Android VMs. So we skip testing there. + * Android VMs and in open-source guava-android. So we skip testing there. */ - if (isAndroid() && Reflection.getPackageName(testedClass).startsWith("com.google.common")) { + if (Reflection.getPackageName(testedClass).startsWith("com.google.common")) { return; } if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) { @@ -604,47 +602,27 @@ public final class NullPointerTester { * Looks for declaration nullness annotations and, if supported, type-use nullness annotations. * * <p>Under Android VMs, the methods for retrieving type-use annotations don't exist. This means - * that {@link NullPointerException} may misbehave under Android when used on classes that rely on + * that {@link NullPointerTester} may misbehave under Android when used on classes that rely on * type-use annotations. * * <p>Under j2objc, the necessary APIs exist, but some (perhaps all) return stub values, like - * empty arrays. Presumably {@link NullPointerException} could likewise misbehave under j2objc, - * but I don't know that anyone uses it there, anyway. + * empty arrays. Presumably {@link NullPointerTester} could likewise misbehave under j2objc, but I + * don't know that anyone uses it there, anyway. */ private enum NullnessAnnotationReader { - // Usages (which are unsafe only for Android) are guarded by the annotatedTypeExists() check. - @SuppressWarnings({"Java7ApiChecker", "AndroidApiChecker", "DoNotCall", "deprecation"}) + @SuppressWarnings("Java7ApiChecker") FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS { @Override - @IgnoreJRERequirement boolean isNullable(Invokable<?, ?> invokable) { return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(invokable) - || containsNullable(invokable.getAnnotatedReturnType().getAnnotations()); + ; // TODO(cpovirk): Should we also check isNullableTypeVariable? } @Override - @IgnoreJRERequirement boolean isNullable(Parameter param) { return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(param) - || containsNullable(param.getAnnotatedType().getAnnotations()) - || isNullableTypeVariable(param.getAnnotatedType().getType()); - } - - @IgnoreJRERequirement - boolean isNullableTypeVariable(Type type) { - if (!(type instanceof TypeVariable)) { - return false; - } - TypeVariable<?> typeVar = (TypeVariable<?>) type; - for (AnnotatedType bound : typeVar.getAnnotatedBounds()) { - // Until Java 15, the isNullableTypeVariable case here won't help: - // https://bugs.openjdk.java.net/browse/JDK-8202469 - if (containsNullable(bound.getAnnotations()) || isNullableTypeVariable(bound.getType())) { - return true; - } - } - return false; + ; } }, FROM_DECLARATION_ANNOTATIONS_ONLY { @@ -663,9 +641,4 @@ public final class NullPointerTester { abstract boolean isNullable(Parameter param); } - - private static boolean isAndroid() { - // Arguably it would make more sense to test "can we see type-use annotations" directly.... - return checkNotNull(System.getProperty("java.runtime.name", "")).contains("Android"); - } } diff --git a/android/guava-testlib/src/com/google/common/testing/Platform.java b/android/guava-testlib/src/com/google/common/testing/Platform.java index bbad5598d..9726d2de0 100644 --- a/android/guava-testlib/src/com/google/common/testing/Platform.java +++ b/android/guava-testlib/src/com/google/common/testing/Platform.java @@ -17,6 +17,7 @@ package com.google.common.testing; import static com.google.common.base.Preconditions.checkNotNull; +import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import java.io.ByteArrayInputStream; @@ -42,7 +43,7 @@ final class Platform { ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(object); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())); - return (T) in.readObject(); + return (T) requireNonNull(in.readObject()); } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } diff --git a/android/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java b/android/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java index abe419e05..325388342 100644 --- a/android/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java +++ b/android/guava-testlib/src/com/google/common/util/concurrent/testing/AbstractListenableFutureTest.java @@ -18,6 +18,7 @@ package com.google.common.util.concurrent.testing; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtIncompatible; import com.google.common.util.concurrent.ListenableFuture; @@ -70,29 +71,17 @@ public abstract class AbstractListenableFutureTest extends TestCase { assertFalse(future.isDone()); assertFalse(future.isCancelled()); - CountDownLatch successLatch = new CountDownLatch(1); - Throwable[] badness = new Throwable[1]; - - // Wait on the future in a separate thread. - new Thread( - () -> { - try { - assertSame(Boolean.TRUE, future.get()); - successLatch.countDown(); - } catch (Throwable t) { - t.printStackTrace(); - badness[0] = t; - } - }) - .start(); + ExecutorService executor = Executors.newSingleThreadExecutor(); - // Release the future value. - latch.countDown(); + try { + Future<Boolean> getResult = executor.submit(() -> future.get()); - assertTrue(successLatch.await(10, SECONDS)); + // Release the future value. + latch.countDown(); - if (badness[0] != null) { - throw badness[0]; + assertTrue(getResult.get(10, SECONDS)); + } finally { + executor.shutdownNow(); } assertTrue(future.isDone()); @@ -127,13 +116,8 @@ public abstract class AbstractListenableFutureTest extends TestCase { // Run cancellation in a separate thread as an extra thread-safety test. new Thread( () -> { - try { - future.get(); - } catch (CancellationException expected) { - successLatch.countDown(); - } catch (Exception ignored) { - // All other errors are ignored, we expect a cancellation. - } + assertThrows(CancellationException.class, future::get); + successLatch.countDown(); }) .start(); @@ -160,13 +144,8 @@ public abstract class AbstractListenableFutureTest extends TestCase { new Thread( () -> { - try { - future.get(); - } catch (CancellationException expected) { - successLatch.countDown(); - } catch (Exception ignored) { - // No success latch count down. - } + assertThrows(CancellationException.class, future::get); + successLatch.countDown(); }) .start(); diff --git a/android/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java b/android/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java index 37af90bda..130e86f87 100644 --- a/android/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java +++ b/android/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java @@ -17,6 +17,7 @@ package com.google.common.collect.testing.features; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; @@ -28,7 +29,9 @@ import java.util.Collections; import java.util.Set; import junit.framework.TestCase; -/** @author George van den Driessche */ +/** + * @author George van den Driessche + */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") public class FeatureUtilTest extends TestCase { @@ -232,27 +235,26 @@ public class FeatureUtilTest extends TestCase { @AndroidIncompatible // Android runs ExampleDerivedInterfaceTester directly if it exists public void testBuildTesterRequirements_classClassConflict() throws Exception { - try { - FeatureUtil.buildTesterRequirements( - ConflictingRequirementsExampleDerivedInterfaceTester.class); - fail("Expected ConflictingRequirementsException"); - } catch (ConflictingRequirementsException e) { - assertThat(e.getConflicts()).contains(ExampleBaseFeature.BASE_FEATURE_1); - assertEquals(ConflictingRequirementsExampleDerivedInterfaceTester.class, e.getSource()); - } + ConflictingRequirementsException e = + assertThrows( + ConflictingRequirementsException.class, + () -> + FeatureUtil.buildTesterRequirements( + ConflictingRequirementsExampleDerivedInterfaceTester.class)); + assertThat(e.getConflicts()).contains(ExampleBaseFeature.BASE_FEATURE_1); + assertEquals(ConflictingRequirementsExampleDerivedInterfaceTester.class, e.getSource()); } @AndroidIncompatible // Android runs ExampleDerivedInterfaceTester directly if it exists public void testBuildTesterRequirements_methodClassConflict() throws Exception { final Method method = ExampleDerivedInterfaceTester.class.getMethod("testRequiringConflictingFeatures"); - try { - FeatureUtil.buildTesterRequirements(method); - fail("Expected ConflictingRequirementsException"); - } catch (ConflictingRequirementsException e) { - assertThat(e.getConflicts()).contains(ExampleBaseFeature.BASE_FEATURE_1); - assertEquals(method, e.getSource()); - } + ConflictingRequirementsException e = + assertThrows( + ConflictingRequirementsException.class, + () -> FeatureUtil.buildTesterRequirements(method)); + assertThat(e.getConflicts()).contains(ExampleBaseFeature.BASE_FEATURE_1); + assertEquals(method, e.getSource()); } @AndroidIncompatible // Android runs ExampleDerivedInterfaceTester directly if it exists diff --git a/android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java b/android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java index 4dc80848f..8387d1d57 100644 --- a/android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java +++ b/android/guava-testlib/test/com/google/common/testing/ArbitraryInstancesTest.java @@ -17,6 +17,7 @@ package com.google.common.testing; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.base.CharMatcher; import com.google.common.base.Charsets; @@ -278,11 +279,7 @@ public class ArbitraryInstancesTest extends TestCase { Comparable<Object> comparable = ArbitraryInstances.get(Comparable.class); assertEquals(0, comparable.compareTo(comparable)); assertTrue(comparable.compareTo("") > 0); - try { - comparable.compareTo(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> comparable.compareTo(null)); } public void testGet_array() { diff --git a/android/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java b/android/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java deleted file mode 100644 index fee11890b..000000000 --- a/android/guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java +++ /dev/null @@ -1,1351 +0,0 @@ -/* - * Copyright (C) 2012 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.testing; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.truth.Truth.assertThat; - -import com.google.common.base.Functions; -import com.google.common.base.Optional; -import com.google.common.collect.ImmutableList; -import com.google.common.testing.ClassSanityTester.FactoryMethodReturnsNullException; -import com.google.common.testing.ClassSanityTester.ParameterHasNoDistinctValueException; -import com.google.common.testing.ClassSanityTester.ParameterNotInstantiableException; -import com.google.common.testing.NullPointerTester.Visibility; -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; -import java.util.AbstractList; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; -import org.checkerframework.checker.nullness.qual.Nullable; - -/** - * Unit tests for {@link ClassSanityTester}. - * - * @author Ben Yu - */ -@AndroidIncompatible // NullPointerTester refuses to run for c.g.c under Android -public class ClassSanityTesterTest extends TestCase { - - private final ClassSanityTester tester = new ClassSanityTester(); - - public void testEqualsOnReturnValues_good() throws Exception { - tester.forAllPublicStaticMethods(GoodEqualsFactory.class).testEquals(); - } - - public static class GoodEqualsFactory { - public static Object good( - String a, - int b, - // oneConstantOnly doesn't matter since it's not nullable and can be only 1 value. - @SuppressWarnings("unused") OneConstantEnum oneConstantOnly, - // noConstant doesn't matter since it can only be null - @SuppressWarnings("unused") @Nullable NoConstantEnum noConstant) { - return new GoodEquals(a, b); - } - // instance method ignored - public Object badIgnored() { - return new BadEquals(); - } - // primitive ignored - public int returnsInt() { - throw new UnsupportedOperationException(); - } - // void ignored - public void voidMethod() { - throw new UnsupportedOperationException(); - } - // non-public method ignored - static Object badButNotPublic() { - return new BadEquals(); - } - } - - public void testForAllPublicStaticMethods_noPublicStaticMethods() throws Exception { - try { - tester.forAllPublicStaticMethods(NoPublicStaticMethods.class).testEquals(); - } catch (AssertionFailedError expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "No public static methods that return java.lang.Object or subtype are found in " - + NoPublicStaticMethods.class - + "."); - return; - } - fail(); - } - - public void testEqualsOnReturnValues_bad() throws Exception { - try { - tester.forAllPublicStaticMethods(BadEqualsFactory.class).testEquals(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - private static class BadEqualsFactory { - /** oneConstantOnly matters now since it can be either null or the constant. */ - @SuppressWarnings("unused") // Called by reflection - public static Object bad(String a, int b, @Nullable OneConstantEnum oneConstantOnly) { - return new GoodEquals(a, b); - } - } - - public void testNullsOnReturnValues_good() throws Exception { - tester.forAllPublicStaticMethods(GoodNullsFactory.class).testNulls(); - } - - private static class GoodNullsFactory { - @SuppressWarnings("unused") // Called by reflection - public static Object good(String s) { - return new GoodNulls(s); - } - } - - public void testNullsOnReturnValues_bad() throws Exception { - try { - tester.forAllPublicStaticMethods(BadNullsFactory.class).thatReturn(Object.class).testNulls(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public void testNullsOnReturnValues_returnTypeFiltered() throws Exception { - try { - tester - .forAllPublicStaticMethods(BadNullsFactory.class) - .thatReturn(Iterable.class) - .testNulls(); - } catch (AssertionFailedError expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo( - "No public static methods that return java.lang.Iterable or subtype are found in " - + BadNullsFactory.class - + "."); - return; - } - fail(); - } - - public static class BadNullsFactory { - public static Object bad(@SuppressWarnings("unused") String a) { - return new BadNulls(); - } - } - - @AndroidIncompatible // TODO(cpovirk): ClassNotFoundException... ClassSanityTesterTest$AnInterface - public void testSerializableOnReturnValues_good() throws Exception { - tester.forAllPublicStaticMethods(GoodSerializableFactory.class).testSerializable(); - } - - public static class GoodSerializableFactory { - public static Object good(Runnable r) { - return r; - } - - public static Object good(AnInterface i) { - return i; - } - } - - public void testSerializableOnReturnValues_bad() throws Exception { - try { - tester.forAllPublicStaticMethods(BadSerializableFactory.class).testSerializable(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public static class BadSerializableFactory { - public static Object bad() { - return new Serializable() { - @SuppressWarnings("unused") - private final Object notSerializable = new Object(); - }; - } - } - - public void testEqualsAndSerializableOnReturnValues_equalsIsGoodButNotSerializable() - throws Exception { - try { - tester.forAllPublicStaticMethods(GoodEqualsFactory.class).testEqualsAndSerializable(); - } catch (AssertionFailedError expected) { - return; - } - fail("should have failed"); - } - - public void testEqualsAndSerializableOnReturnValues_serializableButNotEquals() throws Exception { - try { - tester.forAllPublicStaticMethods(GoodSerializableFactory.class).testEqualsAndSerializable(); - } catch (AssertionFailedError expected) { - return; - } - fail("should have failed"); - } - - @AndroidIncompatible // TODO(cpovirk): ClassNotFoundException... ClassSanityTesterTest$AnInterface - public void testEqualsAndSerializableOnReturnValues_good() throws Exception { - tester - .forAllPublicStaticMethods(GoodEqualsAndSerializableFactory.class) - .testEqualsAndSerializable(); - } - - public static class GoodEqualsAndSerializableFactory { - public static Object good(AnInterface s) { - return Functions.constant(s); - } - } - - public void testEqualsForReturnValues_factoryReturnsNullButNotAnnotated() throws Exception { - try { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class).testEquals(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public void testNullsForReturnValues_factoryReturnsNullButNotAnnotated() throws Exception { - try { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class).testNulls(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public void testSerializableForReturnValues_factoryReturnsNullButNotAnnotated() throws Exception { - try { - tester - .forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class) - .testSerializable(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public void testEqualsAndSerializableForReturnValues_factoryReturnsNullButNotAnnotated() - throws Exception { - try { - tester - .forAllPublicStaticMethods(FactoryThatReturnsNullButNotAnnotated.class) - .testEqualsAndSerializable(); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public static class FactoryThatReturnsNullButNotAnnotated { - public static Object bad() { - return null; - } - } - - public void testEqualsForReturnValues_factoryReturnsNullAndAnnotated() throws Exception { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class).testEquals(); - } - - public void testNullsForReturnValues_factoryReturnsNullAndAnnotated() throws Exception { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class).testNulls(); - } - - public void testSerializableForReturnValues_factoryReturnsNullAndAnnotated() throws Exception { - tester.forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class).testSerializable(); - } - - public void testEqualsAndSerializableForReturnValues_factoryReturnsNullAndAnnotated() - throws Exception { - tester - .forAllPublicStaticMethods(FactoryThatReturnsNullAndAnnotated.class) - .testEqualsAndSerializable(); - } - - public static class FactoryThatReturnsNullAndAnnotated { - public static @Nullable Object bad() { - return null; - } - } - - public void testGoodEquals() throws Exception { - tester.testEquals(GoodEquals.class); - } - - public void testEquals_interface() { - tester.testEquals(AnInterface.class); - } - - public void testEquals_abstractClass() { - tester.testEquals(AnAbstractClass.class); - } - - public void testEquals_enum() { - tester.testEquals(OneConstantEnum.class); - } - - public void testBadEquals() throws Exception { - try { - tester.testEquals(BadEquals.class); - } catch (AssertionFailedError expected) { - assertThat(expected).hasMessageThat().contains("create(null)"); - return; - } - fail("should have failed"); - } - - public void testBadEquals_withParameterizedType() throws Exception { - try { - tester.testEquals(BadEqualsWithParameterizedType.class); - } catch (AssertionFailedError expected) { - assertThat(expected).hasMessageThat().contains("create([[1]])"); - return; - } - fail("should have failed"); - } - - public void testBadEquals_withSingleParameterValue() throws Exception { - try { - tester.doTestEquals(ConstructorParameterWithOptionalNotInstantiable.class); - fail(); - } catch (ParameterHasNoDistinctValueException expected) { - } - } - - public void testGoodReferentialEqualityComparison() throws Exception { - tester.testEquals(UsesEnum.class); - tester.testEquals(UsesReferentialEquality.class); - tester.testEquals(SameListInstance.class); - } - - @AndroidIncompatible // problem with equality of Type objects? - public void testEqualsUsingReferentialEquality() throws Exception { - assertBadUseOfReferentialEquality(SameIntegerInstance.class); - assertBadUseOfReferentialEquality(SameLongInstance.class); - assertBadUseOfReferentialEquality(SameFloatInstance.class); - assertBadUseOfReferentialEquality(SameDoubleInstance.class); - assertBadUseOfReferentialEquality(SameShortInstance.class); - assertBadUseOfReferentialEquality(SameByteInstance.class); - assertBadUseOfReferentialEquality(SameCharacterInstance.class); - assertBadUseOfReferentialEquality(SameBooleanInstance.class); - assertBadUseOfReferentialEquality(SameObjectInstance.class); - assertBadUseOfReferentialEquality(SameStringInstance.class); - assertBadUseOfReferentialEquality(SameInterfaceInstance.class); - } - - private void assertBadUseOfReferentialEquality(Class<?> cls) throws Exception { - try { - tester.testEquals(cls); - } catch (AssertionFailedError expected) { - assertThat(expected).hasMessageThat().contains(cls.getSimpleName() + "("); - return; - } - fail("should have failed for " + cls); - } - - public void testParameterNotInstantiableForEqualsTest() throws Exception { - try { - tester.doTestEquals(ConstructorParameterNotInstantiable.class); - fail("should have failed"); - } catch (ParameterNotInstantiableException expected) { - } - } - - public void testNoDistinctValueForEqualsTest() throws Exception { - try { - tester.doTestEquals(ConstructorParameterSingleValue.class); - fail("should have failed"); - } catch (ParameterHasNoDistinctValueException expected) { - } - } - - public void testConstructorThrowsForEqualsTest() throws Exception { - try { - tester.doTestEquals(ConstructorThrows.class); - fail("should have failed"); - } catch (InvocationTargetException expected) { - } - } - - public void testFactoryMethodReturnsNullForEqualsTest() throws Exception { - try { - tester.doTestEquals(FactoryMethodReturnsNullAndAnnotated.class); - fail("should have failed"); - } catch (FactoryMethodReturnsNullException expected) { - } - } - - public void testFactoryMethodReturnsNullButNotAnnotatedInEqualsTest() throws Exception { - try { - tester.testEquals(FactoryMethodReturnsNullButNotAnnotated.class); - } catch (AssertionFailedError expected) { - return; - } - fail("should have failed"); - } - - public void testNoEqualsChecksOnEnum() throws Exception { - tester.testEquals(OneConstantEnum.class); - tester.testEquals(NoConstantEnum.class); - tester.testEquals(TimeUnit.class); - } - - public void testNoEqualsChecksOnInterface() throws Exception { - tester.testEquals(Runnable.class); - } - - public void testNoEqualsChecksOnAnnotation() throws Exception { - tester.testEquals(MyAnnotation.class); - } - - public void testGoodNulls() throws Exception { - tester.testNulls(GoodNulls.class); - } - - public void testNoNullCheckNeededDespiteNotInstantiable() throws Exception { - tester.doTestNulls(NoNullCheckNeededDespiteNotInstantiable.class, Visibility.PACKAGE); - } - - public void testNulls_interface() { - tester.testNulls(AnInterface.class); - } - - public void testNulls_abstractClass() { - tester.testNulls(AnAbstractClass.class); - } - - public void testNulls_enum() throws Exception { - tester.testNulls(OneConstantEnum.class); - tester.testNulls(NoConstantEnum.class); - tester.testNulls(TimeUnit.class); - } - - public void testNulls_parameterOptionalNotInstantiable() throws Exception { - tester.testNulls(ConstructorParameterWithOptionalNotInstantiable.class); - } - - public void testEnumFailsToCheckNull() throws Exception { - try { - tester.testNulls(EnumFailsToCheckNull.class); - } catch (AssertionFailedError expected) { - return; - } - fail("should have failed"); - } - - public void testNoNullChecksOnInterface() throws Exception { - tester.testNulls(Runnable.class); - } - - public void testNoNullChecksOnAnnotation() throws Exception { - tester.testNulls(MyAnnotation.class); - } - - public void testBadNulls() throws Exception { - try { - tester.testNulls(BadNulls.class); - } catch (AssertionFailedError expected) { - return; - } - fail("should have failed"); - } - - public void testInstantiate_factoryMethodReturnsNullButNotAnnotated() throws Exception { - try { - FactoryMethodReturnsNullButNotAnnotated unused = - tester.instantiate(FactoryMethodReturnsNullButNotAnnotated.class); - } catch (AssertionFailedError expected) { - assertThat(expected).hasMessageThat().contains("@Nullable"); - return; - } - fail("should have failed"); - } - - public void testInstantiate_factoryMethodReturnsNullAndAnnotated() throws Exception { - try { - tester.instantiate(FactoryMethodReturnsNullAndAnnotated.class); - fail("should have failed"); - } catch (FactoryMethodReturnsNullException expected) { - } - } - - public void testInstantiate_factoryMethodAcceptsNull() throws Exception { - assertNull(tester.instantiate(FactoryMethodAcceptsNull.class).name); - } - - public void testInstantiate_factoryMethodDoesNotAcceptNull() throws Exception { - assertNotNull(tester.instantiate(FactoryMethodDoesNotAcceptNull.class).name); - } - - public void testInstantiate_constructorAcceptsNull() throws Exception { - assertNull(tester.instantiate(ConstructorAcceptsNull.class).name); - } - - public void testInstantiate_constructorDoesNotAcceptNull() throws Exception { - assertNotNull(tester.instantiate(ConstructorDoesNotAcceptNull.class).name); - } - - public void testInstantiate_notInstantiable() throws Exception { - assertNull(tester.instantiate(NotInstantiable.class)); - } - - public void testInstantiate_noConstantEnum() throws Exception { - assertNull(tester.instantiate(NoConstantEnum.class)); - } - - public void testInstantiate_oneConstantEnum() throws Exception { - assertEquals(OneConstantEnum.A, tester.instantiate(OneConstantEnum.class)); - } - - public void testInstantiate_interface() throws Exception { - assertNull(tester.instantiate(Runnable.class)); - } - - public void testInstantiate_abstractClass() throws Exception { - assertNull(tester.instantiate(AbstractList.class)); - } - - public void testInstantiate_annotation() throws Exception { - assertNull(tester.instantiate(MyAnnotation.class)); - } - - public void testInstantiate_setDefault() throws Exception { - NotInstantiable x = new NotInstantiable(); - tester.setDefault(NotInstantiable.class, x); - assertNotNull(tester.instantiate(ConstructorParameterNotInstantiable.class)); - } - - public void testSetDistinctValues_equalInstances() { - try { - tester.setDistinctValues(String.class, "", ""); - fail(); - } catch (IllegalArgumentException expected) { - } - } - - public void testInstantiate_setDistinctValues() throws Exception { - NotInstantiable x = new NotInstantiable(); - NotInstantiable y = new NotInstantiable(); - tester.setDistinctValues(NotInstantiable.class, x, y); - assertNotNull(tester.instantiate(ConstructorParameterNotInstantiable.class)); - tester.testEquals(ConstructorParameterMapOfNotInstantiable.class); - } - - public void testInstantiate_constructorThrows() throws Exception { - try { - tester.instantiate(ConstructorThrows.class); - fail(); - } catch (InvocationTargetException expected) { - } - } - - public void testInstantiate_factoryMethodThrows() throws Exception { - try { - tester.instantiate(FactoryMethodThrows.class); - fail(); - } catch (InvocationTargetException expected) { - } - } - - public void testInstantiate_constructorParameterNotInstantiable() throws Exception { - try { - tester.instantiate(ConstructorParameterNotInstantiable.class); - fail(); - } catch (ParameterNotInstantiableException expected) { - } - } - - public void testInstantiate_factoryMethodParameterNotInstantiable() throws Exception { - try { - tester.instantiate(FactoryMethodParameterNotInstantiable.class); - fail(); - } catch (ParameterNotInstantiableException expected) { - } - } - - public void testInstantiate_instantiableFactoryMethodChosen() throws Exception { - assertEquals("good", tester.instantiate(InstantiableFactoryMethodChosen.class).name); - } - - @AndroidIncompatible // TODO(cpovirk): ClassNotFoundException... ClassSanityTesterTest$AnInterface - public void testInterfaceProxySerializable() throws Exception { - SerializableTester.reserializeAndAssert(tester.instantiate(HasAnInterface.class)); - } - - public void testReturnValuesFromAnotherPackageIgnoredForNullTests() throws Exception { - new ClassSanityTester().forAllPublicStaticMethods(JdkObjectFactory.class).testNulls(); - } - - /** String doesn't check nulls as we expect. But the framework should ignore. */ - private static class JdkObjectFactory { - @SuppressWarnings("unused") // Called by reflection - public static Object create() { - return new ArrayList<>(); - } - } - - static class HasAnInterface implements Serializable { - private final AnInterface i; - - public HasAnInterface(AnInterface i) { - this.i = i; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof HasAnInterface) { - HasAnInterface that = (HasAnInterface) obj; - return i.equals(that.i); - } else { - return false; - } - } - - @Override - public int hashCode() { - return i.hashCode(); - } - } - - static class InstantiableFactoryMethodChosen { - final String name; - - private InstantiableFactoryMethodChosen(String name) { - this.name = name; - } - - public InstantiableFactoryMethodChosen(NotInstantiable x) { - checkNotNull(x); - this.name = "x1"; - } - - public static InstantiableFactoryMethodChosen create(NotInstantiable x) { - return new InstantiableFactoryMethodChosen(x); - } - - public static InstantiableFactoryMethodChosen create(String s) { - checkNotNull(s); - return new InstantiableFactoryMethodChosen("good"); - } - } - - public void testInstantiate_instantiableConstructorChosen() throws Exception { - assertEquals("good", tester.instantiate(InstantiableConstructorChosen.class).name); - } - - public void testEquals_setOfNonInstantiable() throws Exception { - try { - new ClassSanityTester().doTestEquals(SetWrapper.class); - fail(); - } catch (ParameterNotInstantiableException expected) { - } - } - - private abstract static class Wrapper { - private final Object wrapped; - - Wrapper(Object wrapped) { - this.wrapped = checkNotNull(wrapped); - } - - @Override - public boolean equals(@Nullable Object obj) { - // In general getClass().isInstance() is bad for equals. - // But here we fully control the subclasses to ensure symmetry. - if (getClass().isInstance(obj)) { - Wrapper that = (Wrapper) obj; - return wrapped.equals(that.wrapped); - } - return false; - } - - @Override - public int hashCode() { - return wrapped.hashCode(); - } - - @Override - public String toString() { - return wrapped.toString(); - } - } - - private static class SetWrapper extends Wrapper { - public SetWrapper(Set<NotInstantiable> wrapped) { - super(wrapped); - } - } - - static class InstantiableConstructorChosen { - final String name; - - public InstantiableConstructorChosen(String name) { - checkNotNull(name); - this.name = "good"; - } - - public InstantiableConstructorChosen(NotInstantiable x) { - checkNotNull(x); - this.name = "x1"; - } - - public static InstantiableFactoryMethodChosen create(NotInstantiable x) { - return new InstantiableFactoryMethodChosen(x); - } - } - - static class GoodEquals { - - private final String a; - private final int b; - - private GoodEquals(String a, int b) { - this.a = checkNotNull(a); - this.b = b; - } - - // ignored by testEquals() - GoodEquals(@SuppressWarnings("unused") NotInstantiable x) { - this.a = "x"; - this.b = -1; - } - - // will keep trying - public GoodEquals(@SuppressWarnings("unused") NotInstantiable x, int b) { - this.a = "x"; - this.b = b; - } - - // keep trying - @SuppressWarnings("unused") - static GoodEquals create(int a, int b) { - throw new RuntimeException(); - } - - // Good! - static GoodEquals create(String a, int b) { - return new GoodEquals(a, b); - } - - // keep trying - @SuppressWarnings("unused") - public static @Nullable GoodEquals createMayReturnNull(int a, int b) { - return null; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof GoodEquals) { - GoodEquals that = (GoodEquals) obj; - return a.equals(that.a) && b == that.b; - } else { - return false; - } - } - - @Override - public int hashCode() { - return 0; - } - } - - static class BadEquals { - - public BadEquals() {} // ignored by testEquals() since it has less parameters. - - public static BadEquals create(@SuppressWarnings("unused") @Nullable String s) { - return new BadEquals(); - } - - @Override - public boolean equals(@Nullable Object obj) { - return obj instanceof BadEquals; - } - - @Override - public int hashCode() { - return 0; - } - } - - static class SameIntegerInstance { - private final Integer i; - - public SameIntegerInstance(Integer i) { - this.i = checkNotNull(i); - } - - @Override - public int hashCode() { - return i.hashCode(); - } - - @Override - @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"}) - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameIntegerInstance) { - SameIntegerInstance that = (SameIntegerInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameLongInstance { - private final Long i; - - public SameLongInstance(Long i) { - this.i = checkNotNull(i); - } - - @Override - public int hashCode() { - return i.hashCode(); - } - - @Override - @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"}) - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameLongInstance) { - SameLongInstance that = (SameLongInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameFloatInstance { - private final Float i; - - public SameFloatInstance(Float i) { - this.i = checkNotNull(i); - } - - @Override - public int hashCode() { - return i.hashCode(); - } - - @Override - @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"}) - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameFloatInstance) { - SameFloatInstance that = (SameFloatInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameDoubleInstance { - private final Double i; - - public SameDoubleInstance(Double i) { - this.i = checkNotNull(i); - } - - @Override - public int hashCode() { - return i.hashCode(); - } - - @Override - @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"}) - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameDoubleInstance) { - SameDoubleInstance that = (SameDoubleInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameShortInstance { - private final Short i; - - public SameShortInstance(Short i) { - this.i = checkNotNull(i); - } - - @Override - public int hashCode() { - return i.hashCode(); - } - - @Override - @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"}) - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameShortInstance) { - SameShortInstance that = (SameShortInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameByteInstance { - private final Byte i; - - public SameByteInstance(Byte i) { - this.i = checkNotNull(i); - } - - @Override - public int hashCode() { - return i.hashCode(); - } - - @Override - @SuppressWarnings({"BoxedPrimitiveEquality", "NumericEquality"}) - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameByteInstance) { - SameByteInstance that = (SameByteInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameCharacterInstance { - private final Character i; - - public SameCharacterInstance(Character i) { - this.i = checkNotNull(i); - } - - @Override - public int hashCode() { - return i.hashCode(); - } - - @Override - @SuppressWarnings("BoxedPrimitiveEquality") - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameCharacterInstance) { - SameCharacterInstance that = (SameCharacterInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameBooleanInstance { - private final Boolean i; - - public SameBooleanInstance(Boolean i) { - this.i = checkNotNull(i); - } - - @Override - public int hashCode() { - return i.hashCode(); - } - - @Override - @SuppressWarnings("BoxedPrimitiveEquality") - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameBooleanInstance) { - SameBooleanInstance that = (SameBooleanInstance) obj; - return i == that.i; - } - return false; - } - } - - static class SameStringInstance { - private final String s; - - public SameStringInstance(String s) { - this.s = checkNotNull(s); - } - - @Override - public int hashCode() { - return s.hashCode(); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameStringInstance) { - SameStringInstance that = (SameStringInstance) obj; - return s == that.s; - } - return false; - } - } - - static class SameObjectInstance { - private final Object s; - - public SameObjectInstance(Object s) { - this.s = checkNotNull(s); - } - - @Override - public int hashCode() { - return s.hashCode(); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameObjectInstance) { - SameObjectInstance that = (SameObjectInstance) obj; - return s == that.s; - } - return false; - } - } - - static class SameInterfaceInstance { - private final Runnable s; - - public SameInterfaceInstance(Runnable s) { - this.s = checkNotNull(s); - } - - @Override - public int hashCode() { - return s.hashCode(); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameInterfaceInstance) { - SameInterfaceInstance that = (SameInterfaceInstance) obj; - return s == that.s; - } - return false; - } - } - - static class SameListInstance { - private final List<?> s; - - public SameListInstance(List<?> s) { - this.s = checkNotNull(s); - } - - @Override - public int hashCode() { - return System.identityHashCode(s); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof SameListInstance) { - SameListInstance that = (SameListInstance) obj; - return s == that.s; - } - return false; - } - } - - static class UsesReferentialEquality { - private final ReferentialEquality s; - - public UsesReferentialEquality(ReferentialEquality s) { - this.s = checkNotNull(s); - } - - @Override - public int hashCode() { - return s.hashCode(); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof UsesReferentialEquality) { - UsesReferentialEquality that = (UsesReferentialEquality) obj; - return s == that.s; - } - return false; - } - } - - static class UsesEnum { - private final TimeUnit s; - - public UsesEnum(TimeUnit s) { - this.s = checkNotNull(s); - } - - @Override - public int hashCode() { - return s.hashCode(); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof UsesEnum) { - UsesEnum that = (UsesEnum) obj; - return s == that.s; - } - return false; - } - } - - public static class ReferentialEquality { - public ReferentialEquality() {} - } - - static class BadEqualsWithParameterizedType { - - // ignored by testEquals() since it has less parameters. - public BadEqualsWithParameterizedType() {} - - public static BadEqualsWithParameterizedType create( - @SuppressWarnings("unused") ImmutableList<Iterable<? extends String>> s) { - return new BadEqualsWithParameterizedType(); - } - - @Override - public boolean equals(@Nullable Object obj) { - return obj instanceof BadEqualsWithParameterizedType; - } - - @Override - public int hashCode() { - return 0; - } - } - - static class GoodNulls { - public GoodNulls(String s) { - checkNotNull(s); - } - - public void rejectNull(String s) { - checkNotNull(s); - } - } - - public static class BadNulls { - public void failsToRejectNull(@SuppressWarnings("unused") String s) {} - } - - public static class NoNullCheckNeededDespiteNotInstantiable { - - public NoNullCheckNeededDespiteNotInstantiable(NotInstantiable x) { - checkNotNull(x); - } - - @SuppressWarnings("unused") // reflected - void primitiveOnly(int i) {} - - @SuppressWarnings("unused") // reflected - void nullableOnly(@Nullable String s) {} - - public void noParameter() {} - - @SuppressWarnings("unused") // reflected - void primitiveAndNullable(@Nullable String s, int i) {} - } - - static class FactoryMethodReturnsNullButNotAnnotated { - private FactoryMethodReturnsNullButNotAnnotated() {} - - static FactoryMethodReturnsNullButNotAnnotated returnsNull() { - return null; - } - } - - static class FactoryMethodReturnsNullAndAnnotated { - private FactoryMethodReturnsNullAndAnnotated() {} - - public static @Nullable FactoryMethodReturnsNullAndAnnotated returnsNull() { - return null; - } - } - - static class FactoryMethodAcceptsNull { - - final String name; - - private FactoryMethodAcceptsNull(String name) { - this.name = name; - } - - static FactoryMethodAcceptsNull create(@Nullable String name) { - return new FactoryMethodAcceptsNull(name); - } - } - - static class FactoryMethodDoesNotAcceptNull { - - final String name; - - private FactoryMethodDoesNotAcceptNull(String name) { - this.name = checkNotNull(name); - } - - public static FactoryMethodDoesNotAcceptNull create(String name) { - return new FactoryMethodDoesNotAcceptNull(name); - } - } - - static class ConstructorAcceptsNull { - - final String name; - - public ConstructorAcceptsNull(@Nullable String name) { - this.name = name; - } - } - - static class ConstructorDoesNotAcceptNull { - - final String name; - - ConstructorDoesNotAcceptNull(String name) { - this.name = checkNotNull(name); - } - } - - static class ConstructorParameterNotInstantiable { - public ConstructorParameterNotInstantiable(@SuppressWarnings("unused") NotInstantiable x) {} - } - - static class ConstructorParameterMapOfNotInstantiable { - private final Map<NotInstantiable, NotInstantiable> m; - - public ConstructorParameterMapOfNotInstantiable(Map<NotInstantiable, NotInstantiable> m) { - this.m = checkNotNull(m); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof ConstructorParameterMapOfNotInstantiable) { - return m.equals(((ConstructorParameterMapOfNotInstantiable) obj).m); - } else { - return false; - } - } - - @Override - public int hashCode() { - return m.hashCode(); - } - } - - // Test that we should get a distinct parameter error when doing equals test. - static class ConstructorParameterWithOptionalNotInstantiable { - public ConstructorParameterWithOptionalNotInstantiable(Optional<NotInstantiable> x) { - checkNotNull(x); - } - - @Override - public boolean equals(@Nullable Object obj) { - throw new UnsupportedOperationException(); - } - - @Override - public int hashCode() { - throw new UnsupportedOperationException(); - } - } - - static class ConstructorParameterSingleValue { - public ConstructorParameterSingleValue(@SuppressWarnings("unused") Singleton s) {} - - @Override - public boolean equals(@Nullable Object obj) { - return obj instanceof ConstructorParameterSingleValue; - } - - @Override - public int hashCode() { - return 1; - } - - public static class Singleton { - public static final Singleton INSTANCE = new Singleton(); - - private Singleton() {} - } - } - - static class FactoryMethodParameterNotInstantiable { - - private FactoryMethodParameterNotInstantiable() {} - - static FactoryMethodParameterNotInstantiable create( - @SuppressWarnings("unused") NotInstantiable x) { - return new FactoryMethodParameterNotInstantiable(); - } - } - - static class ConstructorThrows { - public ConstructorThrows() { - throw new RuntimeException(); - } - } - - static class FactoryMethodThrows { - private FactoryMethodThrows() {} - - public static FactoryMethodThrows create() { - throw new RuntimeException(); - } - } - - static class NotInstantiable { - private NotInstantiable() {} - } - - private enum NoConstantEnum {} - - private enum OneConstantEnum { - A - } - - private enum EnumFailsToCheckNull { - A; - - @SuppressWarnings("unused") - public void failToCheckNull(String s) {} - } - - private interface AnInterface {} - - private abstract static class AnAbstractClass { - @SuppressWarnings("unused") - public AnAbstractClass(String s) {} - - @SuppressWarnings("unused") - public void failsToCheckNull(String s) {} - } - - private static class NoPublicStaticMethods { - @SuppressWarnings("unused") // To test non-public factory isn't used. - static String notPublic() { - return ""; - } - } - - @interface MyAnnotation {} -} diff --git a/android/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java b/android/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java index f100ef483..7628637ab 100644 --- a/android/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java +++ b/android/guava-testlib/test/com/google/common/testing/GcFinalizationTest.java @@ -17,6 +17,7 @@ package com.google.common.testing; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.testing.GcFinalization.FinalizationPredicate; import com.google.common.util.concurrent.SettableFuture; @@ -146,12 +147,9 @@ public class GcFinalizationTest extends TestCase { Interruptenator interruptenator = new Interruptenator(Thread.currentThread()); try { final CountDownLatch latch = new CountDownLatch(1); - try { - GcFinalization.await(latch); - fail("should throw"); - } catch (RuntimeException expected) { - assertWrapsInterruptedException(expected); - } + RuntimeException expected = + assertThrows(RuntimeException.class, () -> GcFinalization.await(latch)); + assertWrapsInterruptedException(expected); } finally { interruptenator.shutdown(); Thread.interrupted(); @@ -162,12 +160,9 @@ public class GcFinalizationTest extends TestCase { Interruptenator interruptenator = new Interruptenator(Thread.currentThread()); try { final SettableFuture<@Nullable Void> future = SettableFuture.create(); - try { - GcFinalization.awaitDone(future); - fail("should throw"); - } catch (RuntimeException expected) { - assertWrapsInterruptedException(expected); - } + RuntimeException expected = + assertThrows(RuntimeException.class, () -> GcFinalization.awaitDone(future)); + assertWrapsInterruptedException(expected); } finally { interruptenator.shutdown(); Thread.interrupted(); @@ -178,12 +173,9 @@ public class GcFinalizationTest extends TestCase { Interruptenator interruptenator = new Interruptenator(Thread.currentThread()); try { final WeakReference<Object> ref = new WeakReference<Object>(Boolean.TRUE); - try { - GcFinalization.awaitClear(ref); - fail("should throw"); - } catch (RuntimeException expected) { - assertWrapsInterruptedException(expected); - } + RuntimeException expected = + assertThrows(RuntimeException.class, () -> GcFinalization.awaitClear(ref)); + assertWrapsInterruptedException(expected); } finally { interruptenator.shutdown(); Thread.interrupted(); @@ -193,17 +185,18 @@ public class GcFinalizationTest extends TestCase { public void testAwaitDone_FinalizationPredicate_Interrupted() { Interruptenator interruptenator = new Interruptenator(Thread.currentThread()); try { - try { - GcFinalization.awaitDone( - new FinalizationPredicate() { - public boolean isDone() { - return false; - } - }); - fail("should throw"); - } catch (RuntimeException expected) { - assertWrapsInterruptedException(expected); - } + RuntimeException expected = + assertThrows( + RuntimeException.class, + () -> + GcFinalization.awaitDone( + new FinalizationPredicate() { + @Override + public boolean isDone() { + return false; + } + })); + assertWrapsInterruptedException(expected); } finally { interruptenator.shutdown(); Thread.interrupted(); diff --git a/android/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java b/android/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java deleted file mode 100644 index d7344abf6..000000000 --- a/android/guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java +++ /dev/null @@ -1,1438 +0,0 @@ -/* - * Copyright (C) 2005 The Guava Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.common.testing; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.truth.Truth.assertThat; - -import com.google.common.base.Converter; -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableMultiset; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSortedSet; -import com.google.common.collect.ImmutableTable; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multiset; -import com.google.common.collect.Table; -import com.google.common.reflect.TypeToken; -import com.google.common.testing.NullPointerTester.Visibility; -import com.google.common.testing.anotherpackage.SomeClassThatDoesNotUseNullable; -import com.google.errorprone.annotations.CanIgnoreReturnValue; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; -import org.checkerframework.checker.nullness.qual.Nullable; - -/** - * Unit test for {@link NullPointerTester}. - * - * @author Kevin Bourrillion - * @author Mick Killianey - */ -@SuppressWarnings("CheckReturnValue") -@AndroidIncompatible // NullPointerTester refuses to run for c.g.c under Android -public class NullPointerTesterTest extends TestCase { - - /** Non-NPE RuntimeException. */ - public static class FooException extends RuntimeException { - private static final long serialVersionUID = 1L; - } - - /** - * Class for testing all permutations of static/non-static one-argument methods using - * methodParameter(). - */ - @SuppressWarnings("unused") // used by reflection - public static class OneArg { - - public static void staticOneArgCorrectlyThrowsNpe(String s) { - checkNotNull(s); // expect NPE here on null - } - - public static void staticOneArgThrowsOtherThanNpe(String s) { - throw new FooException(); // should catch as failure - } - - public static void staticOneArgShouldThrowNpeButDoesnt(String s) { - // should catch as failure - } - - public static void staticOneArgCheckForNullCorrectlyDoesNotThrowNPE( - @javax.annotation.CheckForNull String s) { - // null? no problem - } - - public static void staticOneArgJsr305NullableCorrectlyDoesNotThrowNPE( - @javax.annotation.Nullable String s) { - // null? no problem - } - - public static void staticOneArgNullableCorrectlyDoesNotThrowNPE(@Nullable String s) { - // null? no problem - } - - public static void staticOneArgCheckForNullCorrectlyThrowsOtherThanNPE( - @javax.annotation.CheckForNull String s) { - throw new FooException(); // ok, as long as it's not NullPointerException - } - - public static void staticOneArgNullableCorrectlyThrowsOtherThanNPE(@Nullable String s) { - throw new FooException(); // ok, as long as it's not NullPointerException - } - - public static void staticOneArgCheckForNullThrowsNPE(@javax.annotation.CheckForNull String s) { - checkNotNull(s); // doesn't check if you said you'd accept null, but you don't - } - - public static void staticOneArgNullableThrowsNPE(@Nullable String s) { - checkNotNull(s); // doesn't check if you said you'd accept null, but you don't - } - - public void oneArgCorrectlyThrowsNpe(String s) { - checkNotNull(s); // expect NPE here on null - } - - public void oneArgThrowsOtherThanNpe(String s) { - throw new FooException(); // should catch as failure - } - - public void oneArgShouldThrowNpeButDoesnt(String s) { - // should catch as failure - } - - public void oneArgCheckForNullCorrectlyDoesNotThrowNPE( - @javax.annotation.CheckForNull String s) { - // null? no problem - } - - public void oneArgNullableCorrectlyDoesNotThrowNPE(@Nullable String s) { - // null? no problem - } - - public void oneArgCheckForNullCorrectlyThrowsOtherThanNPE( - @javax.annotation.CheckForNull String s) { - throw new FooException(); // ok, as long as it's not NullPointerException - } - - public void oneArgNullableCorrectlyThrowsOtherThanNPE(@Nullable String s) { - throw new FooException(); // ok, as long as it's not NullPointerException - } - - public void oneArgCheckForNullThrowsNPE(@javax.annotation.CheckForNull String s) { - checkNotNull(s); // doesn't check if you said you'd accept null, but you don't - } - - public void oneArgNullableThrowsNPE(@Nullable String s) { - checkNotNull(s); // doesn't check if you said you'd accept null, but you don't - } - } - - private static final String[] STATIC_ONE_ARG_METHODS_SHOULD_PASS = { - "staticOneArgCorrectlyThrowsNpe", - "staticOneArgCheckForNullCorrectlyDoesNotThrowNPE", - "staticOneArgCheckForNullCorrectlyThrowsOtherThanNPE", - "staticOneArgCheckForNullThrowsNPE", - "staticOneArgNullableCorrectlyDoesNotThrowNPE", - "staticOneArgNullableCorrectlyThrowsOtherThanNPE", - "staticOneArgNullableThrowsNPE", - }; - private static final String[] STATIC_ONE_ARG_METHODS_SHOULD_FAIL = { - "staticOneArgThrowsOtherThanNpe", "staticOneArgShouldThrowNpeButDoesnt", - }; - private static final String[] NONSTATIC_ONE_ARG_METHODS_SHOULD_PASS = { - "oneArgCorrectlyThrowsNpe", - "oneArgCheckForNullCorrectlyDoesNotThrowNPE", - "oneArgCheckForNullCorrectlyThrowsOtherThanNPE", - "oneArgCheckForNullThrowsNPE", - "oneArgNullableCorrectlyDoesNotThrowNPE", - "oneArgNullableCorrectlyThrowsOtherThanNPE", - "oneArgNullableThrowsNPE", - }; - private static final String[] NONSTATIC_ONE_ARG_METHODS_SHOULD_FAIL = { - "oneArgThrowsOtherThanNpe", "oneArgShouldThrowNpeButDoesnt", - }; - - private static class ThrowsIae { - public static void christenPoodle(String name) { - checkArgument(name != null); - } - } - - private static class ThrowsNpe { - public static void christenPoodle(String name) { - checkNotNull(name); - } - } - - private static class ThrowsUoe { - public static void christenPoodle(String name) { - throw new UnsupportedOperationException(); - } - } - - private static class ThrowsSomethingElse { - public static void christenPoodle(String name) { - throw new RuntimeException(); - } - } - - public void testDontAcceptIae() { - NullPointerTester tester = new NullPointerTester(); - tester.testAllPublicStaticMethods(ThrowsNpe.class); - tester.testAllPublicStaticMethods(ThrowsUoe.class); - try { - tester.testAllPublicStaticMethods(ThrowsIae.class); - } catch (AssertionFailedError expected) { - return; - } - fail(); - } - - public void testStaticOneArgMethodsThatShouldPass() throws Exception { - for (String methodName : STATIC_ONE_ARG_METHODS_SHOULD_PASS) { - Method method = OneArg.class.getMethod(methodName, String.class); - try { - new NullPointerTester().testMethodParameter(new OneArg(), method, 0); - } catch (AssertionFailedError unexpected) { - fail("Should not have flagged method " + methodName); - } - } - } - - public void testStaticOneArgMethodsThatShouldFail() throws Exception { - for (String methodName : STATIC_ONE_ARG_METHODS_SHOULD_FAIL) { - Method method = OneArg.class.getMethod(methodName, String.class); - boolean foundProblem = false; - try { - new NullPointerTester().testMethodParameter(new OneArg(), method, 0); - } catch (AssertionFailedError expected) { - foundProblem = true; - } - assertTrue("Should report error in method " + methodName, foundProblem); - } - } - - public void testNonStaticOneArgMethodsThatShouldPass() throws Exception { - OneArg foo = new OneArg(); - for (String methodName : NONSTATIC_ONE_ARG_METHODS_SHOULD_PASS) { - Method method = OneArg.class.getMethod(methodName, String.class); - try { - new NullPointerTester().testMethodParameter(foo, method, 0); - } catch (AssertionFailedError unexpected) { - fail("Should not have flagged method " + methodName); - } - } - } - - public void testNonStaticOneArgMethodsThatShouldFail() throws Exception { - OneArg foo = new OneArg(); - for (String methodName : NONSTATIC_ONE_ARG_METHODS_SHOULD_FAIL) { - Method method = OneArg.class.getMethod(methodName, String.class); - boolean foundProblem = false; - try { - new NullPointerTester().testMethodParameter(foo, method, 0); - } catch (AssertionFailedError expected) { - foundProblem = true; - } - assertTrue("Should report error in method " + methodName, foundProblem); - } - } - - public void testMessageOtherException() throws Exception { - Method method = OneArg.class.getMethod("staticOneArgThrowsOtherThanNpe", String.class); - boolean foundProblem = false; - try { - new NullPointerTester().testMethodParameter(new OneArg(), method, 0); - } catch (AssertionFailedError expected) { - assertThat(expected.getMessage()).contains("index 0"); - assertThat(expected.getMessage()).contains("[null]"); - foundProblem = true; - } - assertTrue("Should report error when different exception is thrown", foundProblem); - } - - public void testMessageNoException() throws Exception { - Method method = OneArg.class.getMethod("staticOneArgShouldThrowNpeButDoesnt", String.class); - boolean foundProblem = false; - try { - new NullPointerTester().testMethodParameter(new OneArg(), method, 0); - } catch (AssertionFailedError expected) { - assertThat(expected.getMessage()).contains("index 0"); - assertThat(expected.getMessage()).contains("[null]"); - foundProblem = true; - } - assertTrue("Should report error when no exception is thrown", foundProblem); - } - - /** - * Class for testing all permutations of nullable/non-nullable two-argument methods using - * testMethod(). - * - * <ul> - * <li>normalNormal: two params, neither is Nullable - * <li>nullableNormal: only first param is Nullable - * <li>normalNullable: only second param is Nullable - * <li>nullableNullable: both params are Nullable - * </ul> - */ - public static class TwoArg { - /** Action to take on a null param. */ - public enum Action { - THROW_A_NPE { - @Override - public void act() { - throw new NullPointerException(); - } - }, - THROW_OTHER { - @Override - public void act() { - throw new FooException(); - } - }, - JUST_RETURN { - @Override - public void act() {} - }; - - public abstract void act(); - } - - Action actionWhenFirstParamIsNull; - Action actionWhenSecondParamIsNull; - - public TwoArg(Action actionWhenFirstParamIsNull, Action actionWhenSecondParamIsNull) { - this.actionWhenFirstParamIsNull = actionWhenFirstParamIsNull; - this.actionWhenSecondParamIsNull = actionWhenSecondParamIsNull; - } - - /** Method that decides how to react to parameters. */ - public void reactToNullParameters(@Nullable Object first, @Nullable Object second) { - if (first == null) { - actionWhenFirstParamIsNull.act(); - } - if (second == null) { - actionWhenSecondParamIsNull.act(); - } - } - - /** Two-arg method with no Nullable params. */ - @SuppressWarnings("GoodTime") // false positive; b/122617528 - public void normalNormal(String first, Integer second) { - reactToNullParameters(first, second); - } - - /** Two-arg method with the second param Nullable. */ - @SuppressWarnings("GoodTime") // false positive; b/122617528 - public void normalNullable(String first, @Nullable Integer second) { - reactToNullParameters(first, second); - } - - /** Two-arg method with the first param Nullable. */ - @SuppressWarnings("GoodTime") // false positive; b/122617528 - public void nullableNormal(@Nullable String first, Integer second) { - reactToNullParameters(first, second); - } - - /** Two-arg method with the both params Nullable. */ - @SuppressWarnings("GoodTime") // false positive; b/122617528 - public void nullableNullable(@Nullable String first, @Nullable Integer second) { - reactToNullParameters(first, second); - } - - /** To provide sanity during debugging. */ - @Override - public String toString() { - return rootLocaleFormat( - "Bar(%s, %s)", actionWhenFirstParamIsNull, actionWhenSecondParamIsNull); - } - } - - public void verifyBarPass(Method method, TwoArg bar) { - try { - new NullPointerTester().testMethod(bar, method); - } catch (AssertionFailedError incorrectError) { - String errorMessage = - rootLocaleFormat("Should not have flagged method %s for %s", method.getName(), bar); - assertNull(errorMessage, incorrectError); - } - } - - public void verifyBarFail(Method method, TwoArg bar) { - try { - new NullPointerTester().testMethod(bar, method); - } catch (AssertionFailedError expected) { - return; // good...we wanted a failure - } - String errorMessage = - rootLocaleFormat("Should have flagged method %s for %s", method.getName(), bar); - fail(errorMessage); - } - - public void testTwoArgNormalNormal() throws Exception { - Method method = TwoArg.class.getMethod("normalNormal", String.class, Integer.class); - for (TwoArg.Action first : TwoArg.Action.values()) { - for (TwoArg.Action second : TwoArg.Action.values()) { - TwoArg bar = new TwoArg(first, second); - if (first.equals(TwoArg.Action.THROW_A_NPE) && second.equals(TwoArg.Action.THROW_A_NPE)) { - verifyBarPass(method, bar); // require both params to throw NPE - } else { - verifyBarFail(method, bar); - } - } - } - } - - public void testTwoArgNormalNullable() throws Exception { - Method method = TwoArg.class.getMethod("normalNullable", String.class, Integer.class); - for (TwoArg.Action first : TwoArg.Action.values()) { - for (TwoArg.Action second : TwoArg.Action.values()) { - TwoArg bar = new TwoArg(first, second); - if (first.equals(TwoArg.Action.THROW_A_NPE)) { - verifyBarPass(method, bar); // only pass if 1st param throws NPE - } else { - verifyBarFail(method, bar); - } - } - } - } - - public void testTwoArgNullableNormal() throws Exception { - Method method = TwoArg.class.getMethod("nullableNormal", String.class, Integer.class); - for (TwoArg.Action first : TwoArg.Action.values()) { - for (TwoArg.Action second : TwoArg.Action.values()) { - TwoArg bar = new TwoArg(first, second); - if (second.equals(TwoArg.Action.THROW_A_NPE)) { - verifyBarPass(method, bar); // only pass if 2nd param throws NPE - } else { - verifyBarFail(method, bar); - } - } - } - } - - public void testTwoArgNullableNullable() throws Exception { - Method method = TwoArg.class.getMethod("nullableNullable", String.class, Integer.class); - for (TwoArg.Action first : TwoArg.Action.values()) { - for (TwoArg.Action second : TwoArg.Action.values()) { - TwoArg bar = new TwoArg(first, second); - verifyBarPass(method, bar); // All args nullable: anything goes! - } - } - } - - /* - * This next part consists of several sample classes that provide - * demonstrations of conditions that cause NullPointerTester - * to succeed/fail. - */ - - /** Lots of well-behaved methods. */ - @SuppressWarnings("unused") // used by reflection - private static class PassObject extends SomeClassThatDoesNotUseNullable { - public static void doThrow(Object arg) { - if (arg == null) { - throw new FooException(); - } - } - - public void noArg() {} - - public void oneArg(String s) { - checkNotNull(s); - } - - void packagePrivateOneArg(String s) { - checkNotNull(s); - } - - protected void protectedOneArg(String s) { - checkNotNull(s); - } - - public void oneNullableArg(@Nullable String s) {} - - public void oneNullableArgThrows(@Nullable String s) { - doThrow(s); - } - - public void twoArg(String s, Integer i) { - checkNotNull(s); - i.intValue(); - } - - public void twoMixedArgs(String s, @Nullable Integer i) { - checkNotNull(s); - } - - public void twoMixedArgs(@Nullable Integer i, String s) { - checkNotNull(s); - } - - public void twoMixedArgsThrows(String s, @Nullable Integer i) { - checkNotNull(s); - doThrow(i); - } - - public void twoMixedArgsThrows(@Nullable Integer i, String s) { - checkNotNull(s); - doThrow(i); - } - - public void twoNullableArgs(@Nullable String s, @javax.annotation.Nullable Integer i) {} - - public void twoNullableArgsThrowsFirstArg(@Nullable String s, @Nullable Integer i) { - doThrow(s); - } - - public void twoNullableArgsThrowsSecondArg(@Nullable String s, @Nullable Integer i) { - doThrow(i); - } - - public static void staticOneArg(String s) { - checkNotNull(s); - } - - public static void staticOneNullableArg(@Nullable String s) {} - - public static void staticOneNullableArgThrows(@Nullable String s) { - doThrow(s); - } - } - - public void testGoodClass() { - shouldPass(new PassObject()); - } - - private static class FailOneArgDoesntThrowNPE extends PassObject { - @Override - public void oneArg(String s) { - // Fail: missing NPE for s - } - } - - public void testFailOneArgDoesntThrowNpe() { - shouldFail(new FailOneArgDoesntThrowNPE()); - } - - private static class FailOneArgThrowsWrongType extends PassObject { - @Override - public void oneArg(String s) { - doThrow(s); // Fail: throwing non-NPE exception for null s - } - } - - public void testFailOneArgThrowsWrongType() { - shouldFail(new FailOneArgThrowsWrongType()); - } - - private static class PassOneNullableArgThrowsNPE extends PassObject { - @Override - public void oneNullableArg(@Nullable String s) { - checkNotNull(s); // ok to throw NPE - } - } - - public void testPassOneNullableArgThrowsNPE() { - shouldPass(new PassOneNullableArgThrowsNPE()); - } - - private static class FailTwoArgsFirstArgDoesntThrowNPE extends PassObject { - @Override - public void twoArg(String s, Integer i) { - // Fail: missing NPE for s - i.intValue(); - } - } - - public void testFailTwoArgsFirstArgDoesntThrowNPE() { - shouldFail(new FailTwoArgsFirstArgDoesntThrowNPE()); - } - - private static class FailTwoArgsFirstArgThrowsWrongType extends PassObject { - @Override - public void twoArg(String s, Integer i) { - doThrow(s); // Fail: throwing non-NPE exception for null s - i.intValue(); - } - } - - public void testFailTwoArgsFirstArgThrowsWrongType() { - shouldFail(new FailTwoArgsFirstArgThrowsWrongType()); - } - - private static class FailTwoArgsSecondArgDoesntThrowNPE extends PassObject { - @Override - public void twoArg(String s, Integer i) { - checkNotNull(s); - // Fail: missing NPE for i - } - } - - public void testFailTwoArgsSecondArgDoesntThrowNPE() { - shouldFail(new FailTwoArgsSecondArgDoesntThrowNPE()); - } - - private static class FailTwoArgsSecondArgThrowsWrongType extends PassObject { - @Override - public void twoArg(String s, Integer i) { - checkNotNull(s); - doThrow(i); // Fail: throwing non-NPE exception for null i - } - } - - public void testFailTwoArgsSecondArgThrowsWrongType() { - shouldFail(new FailTwoArgsSecondArgThrowsWrongType()); - } - - private static class FailTwoMixedArgsFirstArgDoesntThrowNPE extends PassObject { - @Override - public void twoMixedArgs(String s, @Nullable Integer i) { - // Fail: missing NPE for s - } - } - - public void testFailTwoMixedArgsFirstArgDoesntThrowNPE() { - shouldFail(new FailTwoMixedArgsFirstArgDoesntThrowNPE()); - } - - private static class FailTwoMixedArgsFirstArgThrowsWrongType extends PassObject { - @Override - public void twoMixedArgs(String s, @Nullable Integer i) { - doThrow(s); // Fail: throwing non-NPE exception for null s - } - } - - public void testFailTwoMixedArgsFirstArgThrowsWrongType() { - shouldFail(new FailTwoMixedArgsFirstArgThrowsWrongType()); - } - - private static class PassTwoMixedArgsNullableArgThrowsNPE extends PassObject { - @Override - public void twoMixedArgs(String s, @Nullable Integer i) { - checkNotNull(s); - i.intValue(); // ok to throw NPE? - } - } - - public void testPassTwoMixedArgsNullableArgThrowsNPE() { - shouldPass(new PassTwoMixedArgsNullableArgThrowsNPE()); - } - - private static class PassTwoMixedArgSecondNullableArgThrowsOther extends PassObject { - @Override - public void twoMixedArgs(String s, @Nullable Integer i) { - checkNotNull(s); - doThrow(i); // ok to throw non-NPE exception for null i - } - } - - public void testPassTwoMixedArgSecondNullableArgThrowsOther() { - shouldPass(new PassTwoMixedArgSecondNullableArgThrowsOther()); - } - - private static class FailTwoMixedArgsSecondArgDoesntThrowNPE extends PassObject { - @Override - public void twoMixedArgs(@Nullable Integer i, String s) { - // Fail: missing NPE for null s - } - } - - public void testFailTwoMixedArgsSecondArgDoesntThrowNPE() { - shouldFail(new FailTwoMixedArgsSecondArgDoesntThrowNPE()); - } - - private static class FailTwoMixedArgsSecondArgThrowsWrongType extends PassObject { - @Override - public void twoMixedArgs(@Nullable Integer i, String s) { - doThrow(s); // Fail: throwing non-NPE exception for null s - } - } - - public void testFailTwoMixedArgsSecondArgThrowsWrongType() { - shouldFail(new FailTwoMixedArgsSecondArgThrowsWrongType()); - } - - private static class PassTwoNullableArgsFirstThrowsNPE extends PassObject { - @Override - public void twoNullableArgs(@Nullable String s, @Nullable Integer i) { - checkNotNull(s); // ok to throw NPE? - } - } - - public void testPassTwoNullableArgsFirstThrowsNPE() { - shouldPass(new PassTwoNullableArgsFirstThrowsNPE()); - } - - private static class PassTwoNullableArgsFirstThrowsOther extends PassObject { - @Override - public void twoNullableArgs(@Nullable String s, @Nullable Integer i) { - doThrow(s); // ok to throw non-NPE exception for null s - } - } - - public void testPassTwoNullableArgsFirstThrowsOther() { - shouldPass(new PassTwoNullableArgsFirstThrowsOther()); - } - - private static class PassTwoNullableArgsSecondThrowsNPE extends PassObject { - @Override - public void twoNullableArgs(@Nullable String s, @Nullable Integer i) { - i.intValue(); // ok to throw NPE? - } - } - - public void testPassTwoNullableArgsSecondThrowsNPE() { - shouldPass(new PassTwoNullableArgsSecondThrowsNPE()); - } - - private static class PassTwoNullableArgsSecondThrowsOther extends PassObject { - @Override - public void twoNullableArgs(@Nullable String s, @Nullable Integer i) { - doThrow(i); // ok to throw non-NPE exception for null i - } - } - - public void testPassTwoNullableArgsSecondThrowsOther() { - shouldPass(new PassTwoNullableArgsSecondThrowsOther()); - } - - private static class PassTwoNullableArgsNeitherThrowsAnything extends PassObject { - @Override - public void twoNullableArgs(@Nullable String s, @Nullable Integer i) { - // ok to do nothing - } - } - - public void testPassTwoNullableArgsNeitherThrowsAnything() { - shouldPass(new PassTwoNullableArgsNeitherThrowsAnything()); - } - - @SuppressWarnings("unused") // for NullPointerTester - private abstract static class BaseClassThatFailsToThrow { - public void oneArg(String s) {} - } - - private static class SubclassWithBadSuperclass extends BaseClassThatFailsToThrow {} - - public void testSubclassWithBadSuperclass() { - shouldFail(new SubclassWithBadSuperclass()); - } - - @SuppressWarnings("unused") // for NullPointerTester - private abstract static class BaseClassThatFailsToThrowForPackagePrivate { - void packagePrivateOneArg(String s) {} - } - - private static class SubclassWithBadSuperclassForPackagePrivate - extends BaseClassThatFailsToThrowForPackagePrivate {} - - public void testSubclassWithBadSuperclassForPackagePrivateMethod() { - shouldFail(new SubclassWithBadSuperclassForPackagePrivate(), Visibility.PACKAGE); - } - - @SuppressWarnings("unused") // for NullPointerTester - private abstract static class BaseClassThatFailsToThrowForProtected { - protected void protectedOneArg(String s) {} - } - - private static class SubclassWithBadSuperclassForProtected - extends BaseClassThatFailsToThrowForProtected {} - - public void testSubclassWithBadSuperclassForPackageProtectedMethod() { - shouldFail(new SubclassWithBadSuperclassForProtected(), Visibility.PROTECTED); - } - - private static class SubclassThatOverridesBadSuperclassMethod extends BaseClassThatFailsToThrow { - @Override - public void oneArg(@Nullable String s) {} - } - - public void testSubclassThatOverridesBadSuperclassMethod() { - shouldPass(new SubclassThatOverridesBadSuperclassMethod()); - } - - @SuppressWarnings("unused") // for NullPointerTester - private static class SubclassOverridesTheWrongMethod extends BaseClassThatFailsToThrow { - public void oneArg(@Nullable CharSequence s) {} - } - - public void testSubclassOverridesTheWrongMethod() { - shouldFail(new SubclassOverridesTheWrongMethod()); - } - - @SuppressWarnings("unused") // for NullPointerTester - private static class ClassThatFailsToThrowForStatic { - static void staticOneArg(String s) {} - } - - public void testClassThatFailsToThrowForStatic() { - shouldFail(ClassThatFailsToThrowForStatic.class); - } - - private static class SubclassThatFailsToThrowForStatic extends ClassThatFailsToThrowForStatic {} - - public void testSubclassThatFailsToThrowForStatic() { - shouldFail(SubclassThatFailsToThrowForStatic.class); - } - - private static class SubclassThatTriesToOverrideBadStaticMethod - extends ClassThatFailsToThrowForStatic { - static void staticOneArg(@Nullable String s) {} - } - - public void testSubclassThatTriesToOverrideBadStaticMethod() { - shouldFail(SubclassThatTriesToOverrideBadStaticMethod.class); - } - - private static final class HardToCreate { - private HardToCreate(HardToCreate x) {} - } - - @SuppressWarnings("unused") // used by reflection - private static class CanCreateDefault { - public void foo(@Nullable HardToCreate ignored, String required) { - checkNotNull(required); - } - } - - public void testCanCreateDefault() { - shouldPass(new CanCreateDefault()); - } - - @SuppressWarnings("unused") // used by reflection - private static class CannotCreateDefault { - public void foo(HardToCreate ignored, String required) { - checkNotNull(ignored); - checkNotNull(required); - } - } - - public void testCannotCreateDefault() { - shouldFail(new CannotCreateDefault()); - } - - private static void shouldPass(Object instance, Visibility visibility) { - new NullPointerTester().testInstanceMethods(instance, visibility); - } - - private static void shouldPass(Object instance) { - shouldPass(instance, Visibility.PACKAGE); - shouldPass(instance, Visibility.PROTECTED); - shouldPass(instance, Visibility.PUBLIC); - } - - // TODO(cpovirk): eliminate surprising Object/Class overloading of shouldFail - - private static void shouldFail(Object instance, Visibility visibility) { - try { - new NullPointerTester().testInstanceMethods(instance, visibility); - } catch (AssertionFailedError expected) { - return; - } - fail("Should detect problem in " + instance.getClass().getSimpleName()); - } - - private static void shouldFail(Object instance) { - shouldFail(instance, Visibility.PACKAGE); - shouldFail(instance, Visibility.PROTECTED); - shouldFail(instance, Visibility.PUBLIC); - } - - private static void shouldFail(Class<?> cls, Visibility visibility) { - try { - new NullPointerTester().testStaticMethods(cls, visibility); - } catch (AssertionFailedError expected) { - return; - } - fail("Should detect problem in " + cls.getSimpleName()); - } - - private static void shouldFail(Class<?> cls) { - shouldFail(cls, Visibility.PACKAGE); - } - - @SuppressWarnings("unused") // used by reflection - private static class PrivateClassWithPrivateConstructor { - private PrivateClassWithPrivateConstructor(@Nullable Integer argument) {} - } - - public void testPrivateClass() { - NullPointerTester tester = new NullPointerTester(); - for (Constructor<?> constructor : - PrivateClassWithPrivateConstructor.class.getDeclaredConstructors()) { - tester.testConstructor(constructor); - } - } - - private interface Foo<T> { - void doSomething(T bar, Integer baz); - } - - private static class StringFoo implements Foo<String> { - - @Override - public void doSomething(String bar, Integer baz) { - checkNotNull(bar); - checkNotNull(baz); - } - } - - public void testBridgeMethodIgnored() { - new NullPointerTester().testAllPublicInstanceMethods(new StringFoo()); - } - - private abstract static class DefaultValueChecker { - - private final Map<Integer, Object> arguments = Maps.newHashMap(); - - @CanIgnoreReturnValue - final DefaultValueChecker runTester() { - new NullPointerTester().testInstanceMethods(this, Visibility.PACKAGE); - return this; - } - - final void assertNonNullValues(Object... expectedValues) { - assertEquals(expectedValues.length, arguments.size()); - for (int i = 0; i < expectedValues.length; i++) { - assertEquals("Default value for parameter #" + i, expectedValues[i], arguments.get(i)); - } - } - - final Object getDefaultParameterValue(int position) { - return arguments.get(position); - } - - final void calledWith(Object... args) { - for (int i = 0; i < args.length; i++) { - if (args[i] != null) { - arguments.put(i, args[i]); - } - } - for (Object arg : args) { - checkNotNull(arg); // to fulfill null check - } - } - } - - private enum Gender { - MALE, - FEMALE - } - - private static class AllDefaultValuesChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkDefaultValuesForTheseTypes( - Gender gender, - Integer integer, - int i, - String string, - CharSequence charSequence, - List<String> list, - ImmutableList<Integer> immutableList, - Map<String, Integer> map, - ImmutableMap<String, String> immutableMap, - Set<String> set, - ImmutableSet<Integer> immutableSet, - SortedSet<Number> sortedSet, - ImmutableSortedSet<Number> immutableSortedSet, - Multiset<String> multiset, - ImmutableMultiset<Integer> immutableMultiset, - Multimap<String, Integer> multimap, - ImmutableMultimap<String, Integer> immutableMultimap, - Table<String, Integer, Exception> table, - ImmutableTable<Integer, String, Exception> immutableTable) { - calledWith( - gender, - integer, - i, - string, - charSequence, - list, - immutableList, - map, - immutableMap, - set, - immutableSet, - sortedSet, - immutableSortedSet, - multiset, - immutableMultiset, - multimap, - immutableMultimap, - table, - immutableTable); - } - - final void check() { - runTester() - .assertNonNullValues( - Gender.MALE, - Integer.valueOf(0), - 0, - "", - "", - ImmutableList.of(), - ImmutableList.of(), - ImmutableMap.of(), - ImmutableMap.of(), - ImmutableSet.of(), - ImmutableSet.of(), - ImmutableSortedSet.of(), - ImmutableSortedSet.of(), - ImmutableMultiset.of(), - ImmutableMultiset.of(), - ImmutableMultimap.of(), - ImmutableMultimap.of(), - ImmutableTable.of(), - ImmutableTable.of()); - } - } - - public void testDefaultValues() { - new AllDefaultValuesChecker().check(); - } - - private static class ObjectArrayDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(Object[] array, String s) { - calledWith(array, s); - } - - void check() { - runTester(); - Object[] defaultArray = (Object[]) getDefaultParameterValue(0); - assertThat(defaultArray).isEmpty(); - } - } - - public void testObjectArrayDefaultValue() { - new ObjectArrayDefaultValueChecker().check(); - } - - private static class StringArrayDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(String[] array, String s) { - calledWith(array, s); - } - - void check() { - runTester(); - String[] defaultArray = (String[]) getDefaultParameterValue(0); - assertThat(defaultArray).isEmpty(); - } - } - - public void testStringArrayDefaultValue() { - new StringArrayDefaultValueChecker().check(); - } - - private static class IntArrayDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(int[] array, String s) { - calledWith(array, s); - } - - void check() { - runTester(); - int[] defaultArray = (int[]) getDefaultParameterValue(0); - assertEquals(0, defaultArray.length); - } - } - - public void testIntArrayDefaultValue() { - new IntArrayDefaultValueChecker().check(); - } - - private enum EmptyEnum {} - - private static class EmptyEnumDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(EmptyEnum object, String s) { - calledWith(object, s); - } - - void check() { - try { - runTester(); - } catch (AssertionFailedError expected) { - return; - } - fail("Should have failed because enum has no constant"); - } - } - - public void testEmptyEnumDefaultValue() { - new EmptyEnumDefaultValueChecker().check(); - } - - private static class GenericClassTypeDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(Class<? extends List<?>> cls, String s) { - calledWith(cls, s); - } - - void check() { - runTester(); - Class<?> defaultClass = (Class<?>) getDefaultParameterValue(0); - assertEquals(List.class, defaultClass); - } - } - - public void testGenericClassDefaultValue() { - new GenericClassTypeDefaultValueChecker().check(); - } - - private static class NonGenericClassTypeDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(@SuppressWarnings("rawtypes") Class cls, String s) { - calledWith(cls, s); - } - - void check() { - runTester(); - Class<?> defaultClass = (Class<?>) getDefaultParameterValue(0); - assertEquals(Object.class, defaultClass); - } - } - - public void testNonGenericClassDefaultValue() { - new NonGenericClassTypeDefaultValueChecker().check(); - } - - private static class GenericTypeTokenDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(TypeToken<? extends List<? super Number>> type, String s) { - calledWith(type, s); - } - - void check() { - runTester(); - TypeToken<?> defaultType = (TypeToken<?>) getDefaultParameterValue(0); - assertTrue(new TypeToken<List<? super Number>>() {}.isSupertypeOf(defaultType)); - } - } - - public void testGenericTypeTokenDefaultValue() { - new GenericTypeTokenDefaultValueChecker().check(); - } - - private static class NonGenericTypeTokenDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(@SuppressWarnings("rawtypes") TypeToken type, String s) { - calledWith(type, s); - } - - void check() { - runTester(); - TypeToken<?> defaultType = (TypeToken<?>) getDefaultParameterValue(0); - assertEquals(new TypeToken<Object>() {}, defaultType); - } - } - - public void testNonGenericTypeTokenDefaultValue() { - new NonGenericTypeTokenDefaultValueChecker().check(); - } - - private interface FromTo<F, T> extends Function<F, T> {} - - private static class GenericInterfaceDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(FromTo<String, Integer> f, String s) { - calledWith(f, s); - } - - void check() { - runTester(); - FromTo<?, ?> defaultFunction = (FromTo<?, ?>) getDefaultParameterValue(0); - assertEquals(0, defaultFunction.apply(null)); - } - } - - public void testGenericInterfaceDefaultValue() { - new GenericInterfaceDefaultValueChecker().check(); - } - - private interface NullRejectingFromTo<F, T> extends Function<F, T> { - @Override - public abstract T apply(F from); - } - - private static class NullRejectingInterfaceDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(NullRejectingFromTo<String, Integer> f, String s) { - calledWith(f, s); - } - - void check() { - runTester(); - NullRejectingFromTo<?, ?> defaultFunction = - (NullRejectingFromTo<?, ?>) getDefaultParameterValue(0); - assertNotNull(defaultFunction); - try { - defaultFunction.apply(null); - fail("Proxy Should have rejected null"); - } catch (NullPointerException expected) { - } - } - } - - public void testNullRejectingInterfaceDefaultValue() { - new NullRejectingInterfaceDefaultValueChecker().check(); - } - - private static class MultipleInterfacesDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public <T extends FromTo<String, Integer> & Supplier<Long>> void checkArray(T f, String s) { - calledWith(f, s); - } - - void check() { - runTester(); - FromTo<?, ?> defaultFunction = (FromTo<?, ?>) getDefaultParameterValue(0); - assertEquals(0, defaultFunction.apply(null)); - Supplier<?> defaultSupplier = (Supplier<?>) defaultFunction; - assertEquals(Long.valueOf(0), defaultSupplier.get()); - } - } - - public void testMultipleInterfacesDefaultValue() { - new MultipleInterfacesDefaultValueChecker().check(); - } - - private static class GenericInterface2DefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(FromTo<String, FromTo<Integer, String>> f, String s) { - calledWith(f, s); - } - - void check() { - runTester(); - FromTo<?, ?> defaultFunction = (FromTo<?, ?>) getDefaultParameterValue(0); - FromTo<?, ?> returnValue = (FromTo<?, ?>) defaultFunction.apply(null); - assertEquals("", returnValue.apply(null)); - } - } - - public void testGenericInterfaceReturnedByGenericMethod() { - new GenericInterface2DefaultValueChecker().check(); - } - - private abstract static class AbstractGenericDefaultValueChecker<T> extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkGeneric(T value, String s) { - calledWith(value, s); - } - } - - private static class GenericDefaultValueResolvedToStringChecker - extends AbstractGenericDefaultValueChecker<String> { - void check() { - runTester(); - assertEquals("", getDefaultParameterValue(0)); - } - } - - public void testGenericTypeResolvedForDefaultValue() { - new GenericDefaultValueResolvedToStringChecker().check(); - } - - private abstract static class AbstractGenericDefaultValueForPackagePrivateMethodChecker<T> - extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - void checkGeneric(T value, String s) { - calledWith(value, s); - } - } - - private static class DefaultValueForPackagePrivateMethodResolvedToStringChecker - extends AbstractGenericDefaultValueForPackagePrivateMethodChecker<String> { - void check() { - runTester(); - assertEquals("", getDefaultParameterValue(0)); - } - } - - public void testDefaultValueResolvedForPackagePrivateMethod() { - new DefaultValueForPackagePrivateMethodResolvedToStringChecker().check(); - } - - private static class ConverterDefaultValueChecker extends DefaultValueChecker { - - @SuppressWarnings("unused") // called by NullPointerTester - public void checkArray(Converter<String, Integer> c, String s) { - calledWith(c, s); - } - - void check() { - runTester(); - @SuppressWarnings("unchecked") // We are checking it anyway - Converter<String, Integer> defaultConverter = - (Converter<String, Integer>) getDefaultParameterValue(0); - assertEquals(Integer.valueOf(0), defaultConverter.convert("anything")); - assertEquals("", defaultConverter.reverse().convert(123)); - assertNull(defaultConverter.convert(null)); - assertNull(defaultConverter.reverse().convert(null)); - } - } - - public void testConverterDefaultValue() { - new ConverterDefaultValueChecker().check(); - } - - private static class VisibilityMethods { - - @SuppressWarnings("unused") // Called by reflection - private void privateMethod() {} - - @SuppressWarnings("unused") // Called by reflection - void packagePrivateMethod() {} - - @SuppressWarnings("unused") // Called by reflection - protected void protectedMethod() {} - - @SuppressWarnings("unused") // Called by reflection - public void publicMethod() {} - } - - public void testVisibility_public() throws Exception { - assertFalse( - Visibility.PUBLIC.isVisible(VisibilityMethods.class.getDeclaredMethod("privateMethod"))); - assertFalse( - Visibility.PUBLIC.isVisible( - VisibilityMethods.class.getDeclaredMethod("packagePrivateMethod"))); - assertFalse( - Visibility.PUBLIC.isVisible(VisibilityMethods.class.getDeclaredMethod("protectedMethod"))); - assertTrue( - Visibility.PUBLIC.isVisible(VisibilityMethods.class.getDeclaredMethod("publicMethod"))); - } - - public void testVisibility_protected() throws Exception { - assertFalse( - Visibility.PROTECTED.isVisible(VisibilityMethods.class.getDeclaredMethod("privateMethod"))); - assertFalse( - Visibility.PROTECTED.isVisible( - VisibilityMethods.class.getDeclaredMethod("packagePrivateMethod"))); - assertTrue( - Visibility.PROTECTED.isVisible( - VisibilityMethods.class.getDeclaredMethod("protectedMethod"))); - assertTrue( - Visibility.PROTECTED.isVisible(VisibilityMethods.class.getDeclaredMethod("publicMethod"))); - } - - public void testVisibility_package() throws Exception { - assertFalse( - Visibility.PACKAGE.isVisible(VisibilityMethods.class.getDeclaredMethod("privateMethod"))); - assertTrue( - Visibility.PACKAGE.isVisible( - VisibilityMethods.class.getDeclaredMethod("packagePrivateMethod"))); - assertTrue( - Visibility.PACKAGE.isVisible(VisibilityMethods.class.getDeclaredMethod("protectedMethod"))); - assertTrue( - Visibility.PACKAGE.isVisible(VisibilityMethods.class.getDeclaredMethod("publicMethod"))); - } - - private class Inner { - public Inner(String s) { - checkNotNull(s); - } - } - - public void testNonStaticInnerClass() { - try { - new NullPointerTester().testAllPublicConstructors(Inner.class); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("inner class"); - } - } - - private static String rootLocaleFormat(String format, Object... args) { - return String.format(Locale.ROOT, format, args); - } - - static class OverridesEquals { - @SuppressWarnings("EqualsHashCode") - @Override - public boolean equals(@Nullable Object o) { - return true; - } - } - - static class DoesNotOverrideEquals { - public boolean equals(Object a, Object b) { - return true; - } - } - - public void testEqualsMethod() { - shouldPass(new OverridesEquals()); - shouldFail(new DoesNotOverrideEquals()); - } - - private static final class FailOnOneOfTwoConstructors { - @SuppressWarnings("unused") // Called by reflection - public FailOnOneOfTwoConstructors(String s) {} - - @SuppressWarnings("unused") // Called by reflection - public FailOnOneOfTwoConstructors(Object o) { - checkNotNull(o); - } - } - - public void testConstructor_Ignored_ShouldPass() throws Exception { - new NullPointerTester() - .ignore(FailOnOneOfTwoConstructors.class.getDeclaredConstructor(String.class)) - .testAllPublicConstructors(FailOnOneOfTwoConstructors.class); - } - - public void testConstructor_ShouldFail() throws Exception { - try { - new NullPointerTester().testAllPublicConstructors(FailOnOneOfTwoConstructors.class); - } catch (AssertionFailedError expected) { - return; - } - fail("Should detect problem in " + FailOnOneOfTwoConstructors.class.getSimpleName()); - } -} diff --git a/android/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java b/android/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java index bd823f8f6..17655f6ef 100644 --- a/android/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java +++ b/android/guava-testlib/test/com/google/common/testing/anotherpackage/ForwardingWrapperTesterTest.java @@ -17,6 +17,7 @@ package com.google.common.testing.anotherpackage; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.base.Equivalence; import com.google.common.base.Function; @@ -265,11 +266,11 @@ public class ForwardingWrapperTesterTest extends TestCase { } public void testNotInterfaceType() { - try { - new ForwardingWrapperTester().testForwarding(String.class, Functions.<String>identity()); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> + new ForwardingWrapperTester() + .testForwarding(String.class, Functions.<String>identity())); } public void testNulls() { @@ -583,6 +584,7 @@ public class ForwardingWrapperTesterTest extends TestCase { // A method that is defined to 'return this' @CanIgnoreReturnValue ChainingCalls chainingCall(); + // A method that just happens to return a ChainingCalls object ChainingCalls nonChainingCall(); } diff --git a/android/guava-testlib/test/com/google/common/util/concurrent/testing/TestingExecutorsTest.java b/android/guava-testlib/test/com/google/common/util/concurrent/testing/TestingExecutorsTest.java index 66ad78491..a82aa8710 100644 --- a/android/guava-testlib/test/com/google/common/util/concurrent/testing/TestingExecutorsTest.java +++ b/android/guava-testlib/test/com/google/common/util/concurrent/testing/TestingExecutorsTest.java @@ -16,6 +16,8 @@ package com.google.common.util.concurrent.testing; +import static org.junit.Assert.assertThrows; + import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import java.util.List; @@ -76,12 +78,7 @@ public class TestingExecutorsTest extends TestCase { Future<Boolean> future = futureList.get(0); assertFalse(taskDone); assertTrue(future.isDone()); - try { - future.get(); - fail(); - } catch (CancellationException e) { - // pass - } + assertThrows(CancellationException.class, () -> future.get()); } public void testSameThreadScheduledExecutor() throws ExecutionException, InterruptedException { @@ -110,11 +107,6 @@ public class TestingExecutorsTest extends TestCase { }; Future<?> future = TestingExecutors.sameThreadScheduledExecutor().submit(runnable); - try { - future.get(); - fail("Should have thrown exception"); - } catch (ExecutionException e) { - // pass - } + assertThrows(ExecutionException.class, () -> future.get()); } } |