diff --git a/android/guava-tests/test/com/google/common/base/AbstractIteratorTest.java b/android/guava-tests/test/com/google/common/base/AbstractIteratorTest.java index b1cdae52efca..7dc3d0274017 100644 --- a/android/guava-tests/test/com/google/common/base/AbstractIteratorTest.java +++ b/android/guava-tests/test/com/google/common/base/AbstractIteratorTest.java @@ -16,9 +16,13 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; +import com.google.common.base.TestExceptions.SomeCheckedException; +import com.google.common.base.TestExceptions.SomeUncheckedException; import com.google.common.testing.GcFinalization; import java.lang.ref.WeakReference; import java.util.Iterator; @@ -70,11 +74,7 @@ public Integer computeNext() { // Make sure computeNext() doesn't get invoked again assertFalse(iter.hasNext()); - try { - iter.next(); - fail("no exception thrown"); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, iter::next); } public void testSneakyThrow() throws Exception { @@ -95,21 +95,9 @@ public Integer computeNext() { }; // The first time, the sneakily-thrown exception comes out - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (Exception e) { - if (!(e instanceof SomeCheckedException)) { - throw e; - } - } - + assertThrows(SomeCheckedException.class, iter::hasNext); // But the second time, AbstractIterator itself throws an ISE - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, iter::hasNext); } public void testException() { @@ -123,12 +111,8 @@ public Integer computeNext() { }; // It should pass through untouched - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (SomeUncheckedException e) { - assertSame(exception, e); - } + SomeUncheckedException e = assertThrows(SomeUncheckedException.class, iter::hasNext); + assertSame(exception, e); } public void testExceptionAfterEndOfData() { @@ -140,11 +124,7 @@ public Integer computeNext() { throw new SomeUncheckedException(); } }; - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (SomeUncheckedException expected) { - } + assertThrows(SomeUncheckedException.class, iter::hasNext); } public void testCantRemove() { @@ -164,11 +144,7 @@ public Integer computeNext() { assertEquals(0, (int) iter.next()); - try { - iter.remove(); - fail("No exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, iter::remove); } @@ -196,11 +172,7 @@ protected Integer computeNext() { throw new AssertionError(); } }; - try { - iter.hasNext(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, iter::hasNext); } // Technically we should test other reentrant scenarios (4 combinations of @@ -217,8 +189,4 @@ void throwIt(Throwable t) throws T { } new SneakyThrower().throwIt(t); } - - private static class SomeCheckedException extends Exception {} - - private static class SomeUncheckedException extends RuntimeException {} } diff --git a/android/guava-tests/test/com/google/common/base/AsciiTest.java b/android/guava-tests/test/com/google/common/base/AsciiTest.java index 9e6b0e41ab86..3017289c5077 100644 --- a/android/guava-tests/test/com/google/common/base/AsciiTest.java +++ b/android/guava-tests/test/com/google/common/base/AsciiTest.java @@ -16,6 +16,8 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import junit.framework.TestCase; @@ -98,29 +100,13 @@ public void testTruncate() { } public void testTruncateIllegalArguments() { - try { - Ascii.truncate("foobar", 2, "..."); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ascii.truncate("foobar", 2, "...")); - try { - Ascii.truncate("foobar", 8, "1234567890"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ascii.truncate("foobar", 8, "1234567890")); - try { - Ascii.truncate("foobar", -1, "..."); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ascii.truncate("foobar", -1, "...")); - try { - Ascii.truncate("foobar", -1, ""); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ascii.truncate("foobar", -1, "")); } public void testEqualsIgnoreCase() { diff --git a/android/guava-tests/test/com/google/common/base/FunctionsTest.java b/android/guava-tests/test/com/google/common/base/FunctionsTest.java index 6e70ea710b6a..1241200daafa 100644 --- a/android/guava-tests/test/com/google/common/base/FunctionsTest.java +++ b/android/guava-tests/test/com/google/common/base/FunctionsTest.java @@ -16,6 +16,8 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -70,11 +72,7 @@ public String toString() { return "I'm a string"; } })); - try { - Functions.toStringFunction().apply(null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Functions.toStringFunction().apply(null)); } @J2ktIncompatible @@ -101,11 +99,7 @@ public void testForMapWithoutDefault() { assertEquals(3, function.apply("Three").intValue()); assertNull(function.apply("Null")); - try { - function.apply("Two"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> function.apply("Two")); new EqualsTester() .addEqualityGroup(function, Functions.forMap(map)) @@ -225,17 +219,9 @@ public void testComposition() { Functions.compose(integerToSpanish, japaneseToInteger); assertEquals("Uno", japaneseToSpanish.apply("Ichi")); - try { - japaneseToSpanish.apply("Ni"); - fail(); - } catch (IllegalArgumentException e) { - } + assertThrows(IllegalArgumentException.class, () -> japaneseToSpanish.apply("Ni")); assertEquals("Tres", japaneseToSpanish.apply("San")); - try { - japaneseToSpanish.apply("Shi"); - fail(); - } catch (IllegalArgumentException e) { - } + assertThrows(IllegalArgumentException.class, () -> japaneseToSpanish.apply("Shi")); new EqualsTester() .addEqualityGroup(japaneseToSpanish, Functions.compose(integerToSpanish, japaneseToInteger)) diff --git a/android/guava-tests/test/com/google/common/base/JoinerTest.java b/android/guava-tests/test/com/google/common/base/JoinerTest.java index babc3d6e5b80..36cba68cf32a 100644 --- a/android/guava-tests/test/com/google/common/base/JoinerTest.java +++ b/android/guava-tests/test/com/google/common/base/JoinerTest.java @@ -16,19 +16,19 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Joiner.MapJoiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.testing.NullPointerTester; import java.io.IOException; import java.util.Arrays; -import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @@ -60,33 +60,18 @@ public class JoinerTest extends TestCase { private static final Iterable<@Nullable Integer> ITERABLE_FOUR_NULLS = Arrays.asList((Integer) null, null, null, null); + @SuppressWarnings("JoinIterableIterator") // explicitly testing iterator overload, too public void testNoSpecialNullBehavior() { checkNoOutput(J, ITERABLE_); checkResult(J, ITERABLE_1, "1"); checkResult(J, ITERABLE_12, "1-2"); checkResult(J, ITERABLE_123, "1-2-3"); - try { - J.join(ITERABLE_NULL); - fail(); - } catch (NullPointerException expected) { - } - try { - J.join(ITERABLE_1_NULL_2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> J.join(ITERABLE_NULL)); + assertThrows(NullPointerException.class, () -> J.join(ITERABLE_1_NULL_2)); - try { - J.join(ITERABLE_NULL.iterator()); - fail(); - } catch (NullPointerException expected) { - } - try { - J.join(ITERABLE_1_NULL_2.iterator()); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> J.join(ITERABLE_NULL.iterator())); + assertThrows(NullPointerException.class, () -> J.join(ITERABLE_1_NULL_2.iterator())); } public void testOnCharOverride() { @@ -218,29 +203,17 @@ private static void checkResult(Joiner joiner, Iterable parts, String e public void test_useForNull_skipNulls() { Joiner j = Joiner.on("x").useForNull("y"); - try { - j = j.skipNulls(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, j::skipNulls); } public void test_skipNulls_useForNull() { Joiner j = Joiner.on("x").skipNulls(); - try { - j = j.useForNull("y"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> j.useForNull("y")); } public void test_useForNull_twice() { Joiner j = Joiner.on("x").useForNull("y"); - try { - j = j.useForNull("y"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> j.useForNull("y")); } public void testMap() { @@ -252,11 +225,7 @@ public void testMap() { mapWithNulls.put("a", null); mapWithNulls.put(null, "b"); - try { - j.join(mapWithNulls); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> j.join(mapWithNulls)); assertEquals("a:00;00:b", j.useForNull("00").join(mapWithNulls)); @@ -279,17 +248,9 @@ public void testEntries() { mapWithNulls.put(null, "b"); Set> entriesWithNulls = mapWithNulls.entrySet(); - try { - j.join(entriesWithNulls); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> j.join(entriesWithNulls)); - try { - j.join(entriesWithNulls.iterator()); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> j.join(entriesWithNulls.iterator())); assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls)); assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls.iterator())); @@ -305,11 +266,7 @@ public void testEntries() { public void test_skipNulls_onMap() { Joiner j = Joiner.on(",").skipNulls(); - try { - j.withKeyValueSeparator("/"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> j.withKeyValueSeparator("/")); } private static class DontStringMeBro implements CharSequence { @@ -334,36 +291,6 @@ public String toString() { } } - // Don't do this. - private static class IterableIterator implements Iterable, Iterator { - private static final ImmutableSet INTEGERS = ImmutableSet.of(1, 2, 3, 4); - private final Iterator iterator; - - public IterableIterator() { - this.iterator = iterator(); - } - - @Override - public Iterator iterator() { - return INTEGERS.iterator(); - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public Integer next() { - return iterator.next(); - } - - @Override - public void remove() { - iterator.remove(); - } - } - @GwtIncompatible // StringBuilder.append in GWT invokes Object.toString(), unlike the JRE version. public void testDontConvertCharSequenceToString() { assertEquals("foo,foo", Joiner.on(",").join(new DontStringMeBro(), new DontStringMeBro())); diff --git a/android/guava-tests/test/com/google/common/base/MoreObjectsTest.java b/android/guava-tests/test/com/google/common/base/MoreObjectsTest.java index 8c6d809d114d..9b3bbadd1b7d 100644 --- a/android/guava-tests/test/com/google/common/base/MoreObjectsTest.java +++ b/android/guava-tests/test/com/google/common/base/MoreObjectsTest.java @@ -16,6 +16,8 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -40,11 +42,7 @@ public void testFirstNonNull_withNonNull() { } public void testFirstNonNull_throwsNullPointerException() { - try { - MoreObjects.firstNonNull(null, null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> MoreObjects.firstNonNull(null, null)); } // ToStringHelper's tests are in ToStringHelperTest diff --git a/android/guava-tests/test/com/google/common/base/OptionalTest.java b/android/guava-tests/test/com/google/common/base/OptionalTest.java index 072570ad9c1f..2df1a8e62225 100644 --- a/android/guava-tests/test/com/google/common/base/OptionalTest.java +++ b/android/guava-tests/test/com/google/common/base/OptionalTest.java @@ -16,6 +16,7 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.truth.Truth.assertThat; @@ -51,11 +52,7 @@ public void testOf() { } public void testOf_null() { - try { - Optional.of(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Optional.of(null)); } public void testFromNullable() { @@ -79,11 +76,7 @@ public void testIsPresent_yes() { public void testGet_absent() { Optional optional = Optional.absent(); - try { - optional.get(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, optional::get); } public void testGet_present() { @@ -111,11 +104,7 @@ public void testOr_supplier_absent() { public void testOr_nullSupplier_absent() { Supplier nullSupplier = (Supplier) Suppliers.<@Nullable Object>ofInstance(null); Optional absentOptional = Optional.absent(); - try { - absentOptional.or(nullSupplier); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> absentOptional.or(nullSupplier)); } @SuppressWarnings("OptionalOfRedundantMethod") // Unit tests for Optional @@ -153,20 +142,12 @@ public void testAsSet_absent() { public void testAsSet_presentIsImmutable() { Set presentAsSet = Optional.of("a").asSet(); - try { - presentAsSet.add("b"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> presentAsSet.add("b")); } public void testAsSet_absentIsImmutable() { Set absentAsSet = Optional.absent().asSet(); - try { - absentAsSet.add("foo"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> absentAsSet.add("foo")); } public void testTransform_absent() { @@ -183,34 +164,11 @@ public void testTransform_presentToString() { } public void testTransform_present_functionReturnsNull() { - try { - Optional unused = - Optional.of("a") - .transform( - (Function) - new Function() { - @Override - public @Nullable String apply(String input) { - return null; - } - }); - fail("Should throw if Function returns null."); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Optional.of("a").transform(input -> null)); } public void testTransform_absent_functionReturnsNull() { - assertEquals( - Optional.absent(), - Optional.absent() - .transform( - (Function) - new Function() { - @Override - public @Nullable Object apply(Object input) { - return null; - } - })); + assertEquals(Optional.absent(), Optional.absent().transform(input -> null)); } public void testEqualsAndHashCode() { diff --git a/android/guava-tests/test/com/google/common/base/PreconditionsTest.java b/android/guava-tests/test/com/google/common/base/PreconditionsTest.java index 61776d1f84ed..71845c8e5892 100644 --- a/android/guava-tests/test/com/google/common/base/PreconditionsTest.java +++ b/android/guava-tests/test/com/google/common/base/PreconditionsTest.java @@ -16,8 +16,14 @@ package com.google.common.base; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkElementIndex; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkPositionIndex; +import static com.google.common.base.Preconditions.checkPositionIndexes; +import static com.google.common.base.Preconditions.checkState; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -46,347 +52,248 @@ @GwtCompatible(emulated = true) public class PreconditionsTest extends TestCase { public void testCheckArgument_simple_success() { - Preconditions.checkArgument(true); + checkArgument(true); } public void testCheckArgument_simple_failure() { - try { - Preconditions.checkArgument(false); - fail("no exception thrown"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> checkArgument(false)); } public void testCheckArgument_simpleMessage_success() { - Preconditions.checkArgument(true, IGNORE_ME); + checkArgument(true, IGNORE_ME); } public void testCheckArgument_simpleMessage_failure() { - try { - Preconditions.checkArgument(false, new Message()); - fail("no exception thrown"); - } catch (IllegalArgumentException expected) { - verifySimpleMessage(expected); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> checkArgument(false, new Message())); + verifySimpleMessage(expected); } public void testCheckArgument_nullMessage_failure() { - try { - Preconditions.checkArgument(false, null); - fail("no exception thrown"); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("null"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> checkArgument(false, null)); + assertThat(expected).hasMessageThat().isEqualTo("null"); } public void testCheckArgument_nullMessageWithArgs_failure() { - try { - Preconditions.checkArgument(false, null, "b", "d"); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("null [b, d]"); - } + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> checkArgument(false, null, "b", "d")); + assertThat(e).hasMessageThat().isEqualTo("null [b, d]"); } public void testCheckArgument_nullArgs_failure() { - try { - Preconditions.checkArgument(false, "A %s C %s E", null, null); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A null C null E"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, () -> checkArgument(false, "A %s C %s E", null, null)); + assertThat(e).hasMessageThat().isEqualTo("A null C null E"); } public void testCheckArgument_notEnoughArgs_failure() { - try { - Preconditions.checkArgument(false, "A %s C %s E", "b"); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A b C %s E"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, () -> checkArgument(false, "A %s C %s E", "b")); + assertThat(e).hasMessageThat().isEqualTo("A b C %s E"); } public void testCheckArgument_tooManyArgs_failure() { - try { - Preconditions.checkArgument(false, "A %s C %s E", "b", "d", "f"); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A b C d E [f]"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, + () -> checkArgument(false, "A %s C %s E", "b", "d", "f")); + assertThat(e).hasMessageThat().isEqualTo("A b C d E [f]"); } public void testCheckArgument_singleNullArg_failure() { - try { - Preconditions.checkArgument(false, "A %s C", (Object) null); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A null C"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, () -> checkArgument(false, "A %s C", (Object) null)); + assertThat(e).hasMessageThat().isEqualTo("A null C"); } @J2ktIncompatible // TODO(b/319404022): Allow passing null array as varargs public void testCheckArgument_singleNullArray_failure() { - try { - Preconditions.checkArgument(false, "A %s C", (Object[]) null); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A (Object[])null C"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, () -> checkArgument(false, "A %s C", (Object[]) null)); + assertThat(e).hasMessageThat().isEqualTo("A (Object[])null C"); } public void testCheckArgument_complexMessage_success() { - Preconditions.checkArgument(true, "%s", IGNORE_ME); + checkArgument(true, "%s", IGNORE_ME); } public void testCheckArgument_complexMessage_failure() { - try { - Preconditions.checkArgument(false, FORMAT, 5); - fail("no exception thrown"); - } catch (IllegalArgumentException expected) { - verifyComplexMessage(expected); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> checkArgument(false, FORMAT, 5)); + verifyComplexMessage(expected); } public void testCheckState_simple_success() { - Preconditions.checkState(true); + checkState(true); } public void testCheckState_simple_failure() { - try { - Preconditions.checkState(false); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> checkState(false)); } public void testCheckState_simpleMessage_success() { - Preconditions.checkState(true, IGNORE_ME); + checkState(true, IGNORE_ME); } public void testCheckState_simpleMessage_failure() { - try { - Preconditions.checkState(false, new Message()); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - verifySimpleMessage(expected); - } + IllegalStateException expected = + assertThrows(IllegalStateException.class, () -> checkState(false, new Message())); + verifySimpleMessage(expected); } public void testCheckState_nullMessage_failure() { - try { - Preconditions.checkState(false, null); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("null"); - } + IllegalStateException expected = + assertThrows(IllegalStateException.class, () -> checkState(false, null)); + assertThat(expected).hasMessageThat().isEqualTo("null"); } public void testCheckState_complexMessage_success() { - Preconditions.checkState(true, "%s", IGNORE_ME); + checkState(true, "%s", IGNORE_ME); } public void testCheckState_complexMessage_failure() { - try { - Preconditions.checkState(false, FORMAT, 5); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - verifyComplexMessage(expected); - } + IllegalStateException expected = + assertThrows(IllegalStateException.class, () -> checkState(false, FORMAT, 5)); + verifyComplexMessage(expected); } private static final String NON_NULL_STRING = "foo"; public void testCheckNotNull_simple_success() { - String result = Preconditions.checkNotNull(NON_NULL_STRING); + String result = checkNotNull(NON_NULL_STRING); assertSame(NON_NULL_STRING, result); } public void testCheckNotNull_simple_failure() { - try { - Preconditions.checkNotNull(null); - fail("no exception thrown"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> checkNotNull(null)); } public void testCheckNotNull_simpleMessage_success() { - String result = Preconditions.checkNotNull(NON_NULL_STRING, IGNORE_ME); + String result = checkNotNull(NON_NULL_STRING, IGNORE_ME); assertSame(NON_NULL_STRING, result); } public void testCheckNotNull_simpleMessage_failure() { - try { - Preconditions.checkNotNull(null, new Message()); - fail("no exception thrown"); - } catch (NullPointerException expected) { - verifySimpleMessage(expected); - } + NullPointerException expected = + assertThrows(NullPointerException.class, () -> checkNotNull(null, new Message())); + verifySimpleMessage(expected); } public void testCheckNotNull_complexMessage_success() { - String result = Preconditions.checkNotNull(NON_NULL_STRING, "%s", IGNORE_ME); + String result = checkNotNull(NON_NULL_STRING, "%s", IGNORE_ME); assertSame(NON_NULL_STRING, result); } public void testCheckNotNull_complexMessage_failure() { - try { - Preconditions.checkNotNull(null, FORMAT, 5); - fail("no exception thrown"); - } catch (NullPointerException expected) { - verifyComplexMessage(expected); - } + NullPointerException expected = + assertThrows(NullPointerException.class, () -> checkNotNull(null, FORMAT, 5)); + verifyComplexMessage(expected); } public void testCheckElementIndex_ok() { - assertEquals(0, Preconditions.checkElementIndex(0, 1)); - assertEquals(0, Preconditions.checkElementIndex(0, 2)); - assertEquals(1, Preconditions.checkElementIndex(1, 2)); + assertEquals(0, checkElementIndex(0, 1)); + assertEquals(0, checkElementIndex(0, 2)); + assertEquals(1, checkElementIndex(1, 2)); } public void testCheckElementIndex_badSize() { - try { - Preconditions.checkElementIndex(1, -1); - fail(); - } catch (IllegalArgumentException expected) { - // don't care what the message text is, as this is an invalid usage of - // the Preconditions class, unlike all the other exceptions it throws - } + assertThrows(IllegalArgumentException.class, () -> checkElementIndex(1, -1)); } public void testCheckElementIndex_negative() { - try { - Preconditions.checkElementIndex(-1, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("index (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkElementIndex(-1, 1)); + assertThat(expected).hasMessageThat().isEqualTo("index (-1) must not be negative"); } public void testCheckElementIndex_tooHigh() { - try { - Preconditions.checkElementIndex(1, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("index (1) must be less than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkElementIndex(1, 1)); + assertThat(expected).hasMessageThat().isEqualTo("index (1) must be less than size (1)"); } public void testCheckElementIndex_withDesc_negative() { - try { - Preconditions.checkElementIndex(-1, 1, "foo"); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("foo (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkElementIndex(-1, 1, "foo")); + assertThat(expected).hasMessageThat().isEqualTo("foo (-1) must not be negative"); } public void testCheckElementIndex_withDesc_tooHigh() { - try { - Preconditions.checkElementIndex(1, 1, "foo"); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("foo (1) must be less than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkElementIndex(1, 1, "foo")); + assertThat(expected).hasMessageThat().isEqualTo("foo (1) must be less than size (1)"); } public void testCheckPositionIndex_ok() { - assertEquals(0, Preconditions.checkPositionIndex(0, 0)); - assertEquals(0, Preconditions.checkPositionIndex(0, 1)); - assertEquals(1, Preconditions.checkPositionIndex(1, 1)); + assertEquals(0, checkPositionIndex(0, 0)); + assertEquals(0, checkPositionIndex(0, 1)); + assertEquals(1, checkPositionIndex(1, 1)); } public void testCheckPositionIndex_badSize() { - try { - Preconditions.checkPositionIndex(1, -1); - fail(); - } catch (IllegalArgumentException expected) { - // don't care what the message text is, as this is an invalid usage of - // the Preconditions class, unlike all the other exceptions it throws - } + assertThrows(IllegalArgumentException.class, () -> checkPositionIndex(1, -1)); } public void testCheckPositionIndex_negative() { - try { - Preconditions.checkPositionIndex(-1, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("index (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndex(-1, 1)); + assertThat(expected).hasMessageThat().isEqualTo("index (-1) must not be negative"); } public void testCheckPositionIndex_tooHigh() { - try { - Preconditions.checkPositionIndex(2, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("index (2) must not be greater than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndex(2, 1)); + assertThat(expected).hasMessageThat().isEqualTo("index (2) must not be greater than size (1)"); } public void testCheckPositionIndex_withDesc_negative() { - try { - Preconditions.checkPositionIndex(-1, 1, "foo"); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("foo (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndex(-1, 1, "foo")); + assertThat(expected).hasMessageThat().isEqualTo("foo (-1) must not be negative"); } public void testCheckPositionIndex_withDesc_tooHigh() { - try { - Preconditions.checkPositionIndex(2, 1, "foo"); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("foo (2) must not be greater than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndex(2, 1, "foo")); + assertThat(expected).hasMessageThat().isEqualTo("foo (2) must not be greater than size (1)"); } public void testCheckPositionIndexes_ok() { - Preconditions.checkPositionIndexes(0, 0, 0); - Preconditions.checkPositionIndexes(0, 0, 1); - Preconditions.checkPositionIndexes(0, 1, 1); - Preconditions.checkPositionIndexes(1, 1, 1); + checkPositionIndexes(0, 0, 0); + checkPositionIndexes(0, 0, 1); + checkPositionIndexes(0, 1, 1); + checkPositionIndexes(1, 1, 1); } public void testCheckPositionIndexes_badSize() { - try { - Preconditions.checkPositionIndexes(1, 1, -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> checkPositionIndexes(1, 1, -1)); } public void testCheckPositionIndex_startNegative() { - try { - Preconditions.checkPositionIndexes(-1, 1, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("start index (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndexes(-1, 1, 1)); + assertThat(expected).hasMessageThat().isEqualTo("start index (-1) must not be negative"); } public void testCheckPositionIndexes_endTooHigh() { - try { - Preconditions.checkPositionIndexes(0, 2, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("end index (2) must not be greater than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndexes(0, 2, 1)); + assertThat(expected) + .hasMessageThat() + .isEqualTo("end index (2) must not be greater than size (1)"); } public void testCheckPositionIndexes_reversed() { - try { - Preconditions.checkPositionIndexes(1, 0, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("end index (0) must not be less than start index (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndexes(1, 0, 1)); + assertThat(expected) + .hasMessageThat() + .isEqualTo("end index (0) must not be less than start index (1)"); } @GwtIncompatible("Reflection") @@ -528,20 +435,20 @@ public void overloadSelection() { int anInt = 1; // With a boxed predicate, no overloads can be selected in phase 1 // ambiguous without the call to .booleanValue to unbox the Boolean - Preconditions.checkState(boxedBoolean.booleanValue(), "", 1); + checkState(boxedBoolean.booleanValue(), "", 1); // ambiguous without the cast to Object because the boxed predicate prevents any overload from // being selected in phase 1 - Preconditions.checkState(boxedBoolean, "", (Object) boxedLong); + checkState(boxedBoolean, "", (Object) boxedLong); // ternaries introduce their own problems. because of the ternary (which requires a boxing // operation) no overload can be selected in phase 1. and in phase 2 it is ambiguous since it // matches with the second parameter being boxed and without it being boxed. The cast to Object // avoids this. - Preconditions.checkState(aBoolean, "", aBoolean ? "" : anInt, (Object) anInt); + checkState(aBoolean, "", aBoolean ? "" : anInt, (Object) anInt); // ambiguous without the .booleanValue() call since the boxing forces us into phase 2 resolution short s = 2; - Preconditions.checkState(boxedBoolean.booleanValue(), "", s); + checkState(boxedBoolean.booleanValue(), "", s); } @J2ktIncompatible diff --git a/android/guava-tests/test/com/google/common/base/ReflectionFreeAssertThrows.java b/android/guava-tests/test/com/google/common/base/ReflectionFreeAssertThrows.java new file mode 100644 index 000000000000..7996a8b26fdf --- /dev/null +++ b/android/guava-tests/test/com/google/common/base/ReflectionFreeAssertThrows.java @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2024 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.base; + +import com.google.common.annotations.GwtCompatible; +import com.google.common.annotations.GwtIncompatible; +import com.google.common.annotations.J2ktIncompatible; +import com.google.common.base.TestExceptions.SomeCheckedException; +import com.google.common.base.TestExceptions.SomeError; +import com.google.common.base.TestExceptions.SomeOtherCheckedException; +import com.google.common.base.TestExceptions.SomeUncheckedException; +import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.ExecutionError; +import com.google.common.util.concurrent.UncheckedExecutionException; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.UnsupportedCharsetException; +import java.util.ConcurrentModificationException; +import java.util.NoSuchElementException; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import junit.framework.AssertionFailedError; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Replacements for JUnit's {@code assertThrows} that work under GWT/J2CL. */ +@GwtCompatible(emulated = true) +@ElementTypesAreNonnullByDefault +final class ReflectionFreeAssertThrows { + interface ThrowingRunnable { + void run() throws Throwable; + } + + interface ThrowingSupplier { + @Nullable Object get() throws Throwable; + } + + @CanIgnoreReturnValue + static T assertThrows( + Class expectedThrowable, ThrowingSupplier supplier) { + return doAssertThrows(expectedThrowable, supplier, /* userPassedSupplier= */ true); + } + + @CanIgnoreReturnValue + static T assertThrows( + Class expectedThrowable, ThrowingRunnable runnable) { + return doAssertThrows( + expectedThrowable, + () -> { + runnable.run(); + return null; + }, + /* userPassedSupplier= */ false); + } + + private static T doAssertThrows( + Class expectedThrowable, ThrowingSupplier supplier, boolean userPassedSupplier) { + Predicate predicate = INSTANCE_OF.get(expectedThrowable); + if (predicate == null) { + throw new IllegalArgumentException( + expectedThrowable + + " is not yet supported by ReflectionFreeAssertThrows. Add an entry for it in the" + + " map in that class."); + } + Object result; + try { + result = supplier.get(); + } catch (Throwable t) { + if (predicate.apply(t)) { + // We are careful to set up INSTANCE_OF to match each Predicate to its target Class. + @SuppressWarnings("unchecked") + T caught = (T) t; + return caught; + } + throw new AssertionError( + "expected to throw " + expectedThrowable.getSimpleName() + " but threw " + t, t); + } + if (userPassedSupplier) { + throw new AssertionError( + "expected to throw " + + expectedThrowable.getSimpleName() + + " but returned result: " + + result); + } else { + throw new AssertionError("expected to throw " + expectedThrowable.getSimpleName()); + } + } + + private enum PlatformSpecificExceptionBatch { + PLATFORM { + @GwtIncompatible + @J2ktIncompatible + @Override + // returns the types available in "normal" environments + ImmutableMap, Predicate> exceptions() { + return ImmutableMap.of( + InvocationTargetException.class, + e -> e instanceof InvocationTargetException, + StackOverflowError.class, + e -> e instanceof StackOverflowError); + } + }; + + // used under GWT, etc., since the override of this method does not exist there + ImmutableMap, Predicate> exceptions() { + return ImmutableMap.of(); + } + } + + private static final ImmutableMap, Predicate> INSTANCE_OF = + ImmutableMap., Predicate>builder() + .put(ArithmeticException.class, e -> e instanceof ArithmeticException) + .put( + ArrayIndexOutOfBoundsException.class, + e -> e instanceof ArrayIndexOutOfBoundsException) + .put(ArrayStoreException.class, e -> e instanceof ArrayStoreException) + .put(AssertionFailedError.class, e -> e instanceof AssertionFailedError) + .put(CancellationException.class, e -> e instanceof CancellationException) + .put(ClassCastException.class, e -> e instanceof ClassCastException) + .put( + ConcurrentModificationException.class, + e -> e instanceof ConcurrentModificationException) + .put(ExecutionError.class, e -> e instanceof ExecutionError) + .put(ExecutionException.class, e -> e instanceof ExecutionException) + .put(IllegalArgumentException.class, e -> e instanceof IllegalArgumentException) + .put(IllegalStateException.class, e -> e instanceof IllegalStateException) + .put(IndexOutOfBoundsException.class, e -> e instanceof IndexOutOfBoundsException) + .put(NoSuchElementException.class, e -> e instanceof NoSuchElementException) + .put(NullPointerException.class, e -> e instanceof NullPointerException) + .put(NumberFormatException.class, e -> e instanceof NumberFormatException) + .put(RuntimeException.class, e -> e instanceof RuntimeException) + .put(SomeCheckedException.class, e -> e instanceof SomeCheckedException) + .put(SomeError.class, e -> e instanceof SomeError) + .put(SomeOtherCheckedException.class, e -> e instanceof SomeOtherCheckedException) + .put(SomeUncheckedException.class, e -> e instanceof SomeUncheckedException) + .put(TimeoutException.class, e -> e instanceof TimeoutException) + .put(UncheckedExecutionException.class, e -> e instanceof UncheckedExecutionException) + .put(UnsupportedCharsetException.class, e -> e instanceof UnsupportedCharsetException) + .put(UnsupportedOperationException.class, e -> e instanceof UnsupportedOperationException) + .put(VerifyException.class, e -> e instanceof VerifyException) + .putAll(PlatformSpecificExceptionBatch.PLATFORM.exceptions()) + .buildOrThrow(); + + private ReflectionFreeAssertThrows() {} +} diff --git a/android/guava-tests/test/com/google/common/base/SplitterTest.java b/android/guava-tests/test/com/google/common/base/SplitterTest.java index 052cb5f50a27..b9bf3e8e82a4 100644 --- a/android/guava-tests/test/com/google/common/base/SplitterTest.java +++ b/android/guava-tests/test/com/google/common/base/SplitterTest.java @@ -16,8 +16,8 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -41,11 +41,7 @@ public class SplitterTest extends TestCase { private static final Splitter COMMA_SPLITTER = Splitter.on(','); public void testSplitNullString() { - try { - COMMA_SPLITTER.split(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> COMMA_SPLITTER.split(null)); } public void testCharacterSimpleSplit() { @@ -254,11 +250,7 @@ public void testStringSplitWithDelimiterSubstringInValue() { } public void testStringSplitWithEmptyString() { - try { - Splitter.on(""); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Splitter.on("")); } public void testStringSplitOnEmptyString() { @@ -561,19 +553,11 @@ public void testFixedLengthSplitIntoChars() { } public void testFixedLengthSplitZeroChunkLen() { - try { - Splitter.fixedLength(0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Splitter.fixedLength(0)); } public void testFixedLengthSplitNegativeChunkLen() { - try { - Splitter.fixedLength(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Splitter.fixedLength(-1)); } public void testLimitLarge() { @@ -661,11 +645,7 @@ public void testLimitExtraSeparatorsTrim1EmptyOmit() { } public void testInvalidZeroLimit() { - try { - COMMA_SPLITTER.limit(0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> COMMA_SPLITTER.limit(0)); } @J2ktIncompatible @@ -749,19 +729,13 @@ public void testMapSplitter_multiCharacterSeparator() { } public void testMapSplitter_emptySeparator() { - try { - COMMA_SPLITTER.withKeyValueSeparator(""); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> COMMA_SPLITTER.withKeyValueSeparator("")); } public void testMapSplitter_malformedEntry() { - try { - COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,b,c=2"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,b,c=2")); } /** @@ -769,11 +743,9 @@ public void testMapSplitter_malformedEntry() { * be changed? */ public void testMapSplitter_extraValueDelimiter() { - try { - COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,c=2="); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,c=2=")); } public void testMapSplitter_orderedResults() { @@ -793,11 +765,9 @@ public void testMapSplitter_orderedResults() { } public void testMapSplitter_duplicateKeys() { - try { - COMMA_SPLITTER.withKeyValueSeparator(":").split("a:1,b:2,a:3"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> COMMA_SPLITTER.withKeyValueSeparator(":").split("a:1,b:2,a:3")); } public void testMapSplitter_varyingTrimLevels() { diff --git a/android/guava-tests/test/com/google/common/base/StopwatchTest.java b/android/guava-tests/test/com/google/common/base/StopwatchTest.java index 99e4998d6865..abe0f438fb2a 100644 --- a/android/guava-tests/test/com/google/common/base/StopwatchTest.java +++ b/android/guava-tests/test/com/google/common/base/StopwatchTest.java @@ -16,6 +16,7 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; @@ -59,11 +60,7 @@ public void testStart() { public void testStart_whileRunning() { stopwatch.start(); - try { - stopwatch.start(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, stopwatch::start); assertTrue(stopwatch.isRunning()); } @@ -74,22 +71,14 @@ public void testStop() { } public void testStop_new() { - try { - stopwatch.stop(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, stopwatch::stop); assertFalse(stopwatch.isRunning()); } public void testStop_alreadyStopped() { stopwatch.start(); stopwatch.stop(); - try { - stopwatch.stop(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, stopwatch::stop); assertFalse(stopwatch.isRunning()); } diff --git a/android/guava-tests/test/com/google/common/base/StringsTest.java b/android/guava-tests/test/com/google/common/base/StringsTest.java index 72e441ef8729..494f321c208d 100644 --- a/android/guava-tests/test/com/google/common/base/StringsTest.java +++ b/android/guava-tests/test/com/google/common/base/StringsTest.java @@ -16,6 +16,7 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -72,11 +73,7 @@ public void testPadStart_negativeMinLength() { // TODO: could remove if we got NPT working in GWT somehow public void testPadStart_null() { - try { - Strings.padStart(null, 5, '0'); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Strings.padStart(null, 5, '0')); } public void testPadEnd_noPadding() { @@ -99,15 +96,11 @@ public void testPadEnd_negativeMinLength() { assertSame("x", Strings.padEnd("x", -1, '-')); } - // TODO: could remove if we got NPT working in GWT somehow public void testPadEnd_null() { - try { - Strings.padEnd(null, 5, '0'); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Strings.padEnd(null, 5, '0')); } + @SuppressWarnings("InlineMeInliner") // test of method that doesn't just delegate public void testRepeat() { String input = "20"; assertEquals("", Strings.repeat(input, 0)); @@ -121,28 +114,17 @@ public void testRepeat() { assertEquals(2 * i, Strings.repeat(input, i).length()); } - try { - Strings.repeat("x", -1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - // Massive string - Strings.repeat("12345678", (1 << 30) + 3); - fail(); - } catch (ArrayIndexOutOfBoundsException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Strings.repeat("x", -1)); + assertThrows( + ArrayIndexOutOfBoundsException.class, () -> Strings.repeat("12345678", (1 << 30) + 3)); } - // TODO: could remove if we got NPT working in GWT somehow + @SuppressWarnings("InlineMeInliner") // test of method that doesn't just delegate public void testRepeat_null() { - try { - Strings.repeat(null, 5); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Strings.repeat(null, 5)); } + @SuppressWarnings("UnnecessaryStringBuilder") // We want to test a non-String CharSequence public void testCommonPrefix() { assertEquals("", Strings.commonPrefix("", "")); assertEquals("", Strings.commonPrefix("abc", "")); @@ -152,7 +134,7 @@ public void testCommonPrefix() { assertEquals("", Strings.commonPrefix("xyz", "abcxyz")); assertEquals("a", Strings.commonPrefix("abc", "aaaaa")); assertEquals("aa", Strings.commonPrefix("aa", "aaaaa")); - assertEquals("abc", Strings.commonPrefix(new StringBuffer("abcdef"), "abcxyz")); + assertEquals("abc", Strings.commonPrefix(new StringBuilder("abcdef"), "abcxyz")); // Identical valid surrogate pairs. assertEquals( @@ -172,6 +154,7 @@ public void testCommonPrefix() { assertEquals("\uD8AB", Strings.commonPrefix("\uD8AB", "\uD8AB")); } + @SuppressWarnings("UnnecessaryStringBuilder") // We want to test a non-String CharSequence public void testCommonSuffix() { assertEquals("", Strings.commonSuffix("", "")); assertEquals("", Strings.commonSuffix("abc", "")); @@ -181,7 +164,7 @@ public void testCommonSuffix() { assertEquals("", Strings.commonSuffix("xyz", "xyzabc")); assertEquals("c", Strings.commonSuffix("abc", "ccccc")); assertEquals("aa", Strings.commonSuffix("aa", "aaaaa")); - assertEquals("abc", Strings.commonSuffix(new StringBuffer("xyzabc"), "xxxabc")); + assertEquals("abc", Strings.commonSuffix(new StringBuilder("xyzabc"), "xxxabc")); // Identical valid surrogate pairs. assertEquals( diff --git a/android/guava-tests/test/com/google/common/base/SuppliersTest.java b/android/guava-tests/test/com/google/common/base/SuppliersTest.java index 1954c164c076..8b0313ed62f4 100644 --- a/android/guava-tests/test/com/google/common/base/SuppliersTest.java +++ b/android/guava-tests/test/com/google/common/base/SuppliersTest.java @@ -16,9 +16,9 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -243,35 +243,26 @@ public void testMemoizeWithExpiration_duration() throws InterruptedException { @SuppressWarnings("DoNotCall") public void testMemoizeWithExpiration_longTimeUnitNegative() throws InterruptedException { - try { - Supplier unused = Suppliers.memoizeWithExpiration(() -> "", 0, TimeUnit.MILLISECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Suppliers.memoizeWithExpiration(() -> "", 0, TimeUnit.MILLISECONDS)); - try { - Supplier unused = - Suppliers.memoizeWithExpiration(() -> "", -1, TimeUnit.MILLISECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Suppliers.memoizeWithExpiration(() -> "", -1, TimeUnit.MILLISECONDS)); } @SuppressWarnings("Java7ApiChecker") // test of Java 8+ API @J2ktIncompatible // Duration @GwtIncompatible // Duration public void testMemoizeWithExpiration_durationNegative() throws InterruptedException { - try { - Supplier unused = Suppliers.memoizeWithExpiration(() -> "", Duration.ZERO); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Suppliers.memoizeWithExpiration(() -> "", Duration.ZERO)); - try { - Supplier unused = Suppliers.memoizeWithExpiration(() -> "", Duration.ofMillis(-1)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Suppliers.memoizeWithExpiration(() -> "", Duration.ofMillis(-1))); } @J2ktIncompatible @@ -393,6 +384,7 @@ int waitingThreads() { } @Override + @SuppressWarnings("ThreadPriorityCheck") // doing our best to test for races public Boolean get() { // Check that this method is called exactly once, by the first // thread to synchronize. @@ -438,6 +430,7 @@ public void run() { @J2ktIncompatible @GwtIncompatible // Thread + @SuppressWarnings("ThreadPriorityCheck") // doing our best to test for races public void testSynchronizedSupplierThreadSafe() throws InterruptedException { final Supplier nonThreadSafe = new Supplier() { diff --git a/android/guava-tests/test/com/google/common/base/TestExceptions.java b/android/guava-tests/test/com/google/common/base/TestExceptions.java new file mode 100644 index 000000000000..ae911419bd11 --- /dev/null +++ b/android/guava-tests/test/com/google/common/base/TestExceptions.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2007 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.base; + +import com.google.common.annotations.GwtCompatible; + +/** Exception classes for use in tests. */ +@GwtCompatible +final class TestExceptions { + static class SomeError extends Error {} + + static class SomeCheckedException extends Exception {} + + static class SomeOtherCheckedException extends Exception {} + + static class YetAnotherCheckedException extends Exception {} + + static class SomeUncheckedException extends RuntimeException {} + + static class SomeChainingException extends RuntimeException { + public SomeChainingException(Throwable cause) { + super(cause); + } + } + + private TestExceptions() {} +} diff --git a/android/guava-tests/test/com/google/common/base/ThrowablesTest.java b/android/guava-tests/test/com/google/common/base/ThrowablesTest.java index 1e11f8d3dc67..78fd4affa5d4 100644 --- a/android/guava-tests/test/com/google/common/base/ThrowablesTest.java +++ b/android/guava-tests/test/com/google/common/base/ThrowablesTest.java @@ -16,20 +16,31 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION; +import static com.google.common.base.Throwables.getCausalChain; +import static com.google.common.base.Throwables.getCauseAs; +import static com.google.common.base.Throwables.getRootCause; import static com.google.common.base.Throwables.getStackTraceAsString; import static com.google.common.base.Throwables.lazyStackTrace; import static com.google.common.base.Throwables.lazyStackTraceIsLazy; +import static com.google.common.base.Throwables.propagate; +import static com.google.common.base.Throwables.propagateIfInstanceOf; +import static com.google.common.base.Throwables.propagateIfPossible; import static com.google.common.base.Throwables.throwIfInstanceOf; import static com.google.common.base.Throwables.throwIfUnchecked; import static com.google.common.truth.Truth.assertThat; -import static java.util.Arrays.asList; import static java.util.regex.Pattern.quote; -import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; +import com.google.common.base.TestExceptions.SomeChainingException; +import com.google.common.base.TestExceptions.SomeCheckedException; +import com.google.common.base.TestExceptions.SomeError; +import com.google.common.base.TestExceptions.SomeOtherCheckedException; +import com.google.common.base.TestExceptions.SomeUncheckedException; +import com.google.common.base.TestExceptions.YetAnotherCheckedException; import com.google.common.collect.Iterables; import com.google.common.primitives.Ints; import com.google.common.testing.NullPointerTester; @@ -42,21 +53,15 @@ * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) +@SuppressWarnings("deprecation") // tests of numerous deprecated methods public class ThrowablesTest extends TestCase { public void testThrowIfUnchecked_unchecked() { - try { - throwIfUnchecked(new SomeUncheckedException()); - fail(); - } catch (SomeUncheckedException expected) { - } + assertThrows( + SomeUncheckedException.class, () -> throwIfUnchecked(new SomeUncheckedException())); } public void testThrowIfUnchecked_error() { - try { - throwIfUnchecked(new SomeError()); - fail(); - } catch (SomeError expected) { - } + assertThrows(SomeError.class, () -> throwIfUnchecked(new SomeError())); } @SuppressWarnings("ThrowIfUncheckedKnownChecked") @@ -66,332 +71,126 @@ public void testThrowIfUnchecked_checked() { @J2ktIncompatible @GwtIncompatible // propagateIfPossible - public void testPropagateIfPossible_noneDeclared_noneThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t); - throw new SomeChainingException(t); - } - } - }; - - // Expect no exception to be thrown - sample.noneDeclared(); - } - - @J2ktIncompatible - @GwtIncompatible // propagateIfPossible - public void testPropagateIfPossible_noneDeclared_uncheckedThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t); - throw new SomeChainingException(t); - } - } - }; - - // Expect the unchecked exception to propagate as-is - assertThrows(SomeUncheckedException.class, () -> sample.noneDeclared()); + public void testPropagateIfPossible_noneDeclared_unchecked() { + assertThrows( + SomeUncheckedException.class, () -> propagateIfPossible(new SomeUncheckedException())); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible - public void testPropagateIfPossible_noneDeclared_undeclaredThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsUndeclaredChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t); - throw new SomeChainingException(t); - } - } - }; - - // Expect the undeclared exception to have been chained inside another - assertThrows(SomeChainingException.class, () -> sample.noneDeclared()); + @SuppressWarnings("ThrowIfUncheckedKnownChecked") + public void testPropagateIfPossible_noneDeclared_checked() { + propagateIfPossible(new SomeCheckedException()); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class) - public void testPropagateIfPossible_oneDeclared_noneThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - // yes, this block is never reached, but for purposes of illustration - // we're keeping it the same in each test - Throwables.propagateIfPossible(t, SomeCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect no exception to be thrown - sample.oneDeclared(); + public void testPropagateIfPossible_oneDeclared_unchecked() { + assertThrows( + SomeUncheckedException.class, + () -> propagateIfPossible(new SomeUncheckedException(), SomeCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class) - public void testPropagateIfPossible_oneDeclared_uncheckedThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t, SomeCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the unchecked exception to propagate as-is - assertThrows(SomeUncheckedException.class, () -> sample.oneDeclared()); + public void testPropagateIfPossible_oneDeclared_checkedSame() { + assertThrows( + SomeCheckedException.class, + () -> propagateIfPossible(new SomeCheckedException(), SomeCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class) - public void testPropagateIfPossible_oneDeclared_checkedThrown() { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t, SomeCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the checked exception to propagate as-is - assertThrows(SomeCheckedException.class, () -> sample.oneDeclared()); + public void testPropagateIfPossible_oneDeclared_checkedDifferent() throws SomeCheckedException { + propagateIfPossible(new SomeOtherCheckedException(), SomeCheckedException.class); } @J2ktIncompatible - @GwtIncompatible // propagateIfPossible(Throwable, Class) - public void testPropagateIfPossible_oneDeclared_undeclaredThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsUndeclaredChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t, SomeCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the undeclared exception to have been chained inside another - assertThrows(SomeChainingException.class, () -> sample.oneDeclared()); + @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) + public void testPropagateIfPossible_twoDeclared_unchecked() { + assertThrows( + SomeUncheckedException.class, + () -> + propagateIfPossible( + new SomeUncheckedException(), + SomeCheckedException.class, + SomeOtherCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropagateIfPossible_twoDeclared_noneThrown() - throws SomeCheckedException, SomeOtherCheckedException { - Sample sample = - new Sample() { - @Override - public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - Throwables.propagateIfPossible( - t, SomeCheckedException.class, SomeOtherCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect no exception to be thrown - sample.twoDeclared(); + public void testPropagateIfPossible_twoDeclared_firstSame() { + assertThrows( + SomeCheckedException.class, + () -> + propagateIfPossible( + new SomeCheckedException(), + SomeCheckedException.class, + SomeOtherCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropagateIfPossible_twoDeclared_uncheckedThrown() - throws SomeCheckedException, SomeOtherCheckedException { - Sample sample = - new Sample() { - @Override - public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible( - t, SomeCheckedException.class, SomeOtherCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the unchecked exception to propagate as-is - assertThrows(SomeUncheckedException.class, () -> sample.twoDeclared()); + public void testPropagateIfPossible_twoDeclared_secondSame() { + assertThrows( + SomeOtherCheckedException.class, + () -> + propagateIfPossible( + new SomeOtherCheckedException(), + SomeCheckedException.class, + SomeOtherCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropagateIfPossible_twoDeclared_checkedThrown() throws SomeOtherCheckedException { - Sample sample = - new Sample() { - @Override - public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException { - try { - methodThatThrowsChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible( - t, SomeCheckedException.class, SomeOtherCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the checked exception to propagate as-is - assertThrows(SomeCheckedException.class, () -> sample.twoDeclared()); + public void testPropagateIfPossible_twoDeclared_neitherSame() + throws SomeCheckedException, SomeOtherCheckedException { + propagateIfPossible( + new YetAnotherCheckedException(), + SomeCheckedException.class, + SomeOtherCheckedException.class); } - @J2ktIncompatible - @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropagateIfPossible_twoDeclared_otherCheckedThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException { - try { - methodThatThrowsOtherChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible( - t, SomeCheckedException.class, SomeOtherCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the checked exception to propagate as-is - assertThrows(SomeOtherCheckedException.class, () -> sample.twoDeclared()); - } - - public void testThrowIfUnchecked_null() throws SomeCheckedException { - try { - throwIfUnchecked(null); - fail(); - } catch (NullPointerException expected) { - } + public void testThrowIfUnchecked_null() { + assertThrows(NullPointerException.class, () -> throwIfUnchecked(null)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible - public void testPropageIfPossible_null() throws SomeCheckedException { - Throwables.propagateIfPossible(null); + public void testPropageIfPossible_null() { + propagateIfPossible(null); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class) public void testPropageIfPossible_oneDeclared_null() throws SomeCheckedException { - Throwables.propagateIfPossible(null, SomeCheckedException.class); + propagateIfPossible(null, SomeCheckedException.class); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropageIfPossible_twoDeclared_null() throws SomeCheckedException { - Throwables.propagateIfPossible(null, SomeCheckedException.class, SomeUncheckedException.class); - } - - @J2ktIncompatible - @GwtIncompatible // propagate - public void testPropagate_noneDeclared_noneThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - }; - - // Expect no exception to be thrown - sample.noneDeclared(); + public void testPropageIfPossible_twoDeclared_null() + throws SomeCheckedException, SomeOtherCheckedException { + propagateIfPossible(null, SomeCheckedException.class, SomeOtherCheckedException.class); } @J2ktIncompatible @GwtIncompatible // propagate - public void testPropagate_noneDeclared_uncheckedThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - }; - - // Expect the unchecked exception to propagate as-is - assertThrows(SomeUncheckedException.class, () -> sample.noneDeclared()); + public void testPropagate_noneDeclared_unchecked() { + assertThrows(SomeUncheckedException.class, () -> propagate(new SomeUncheckedException())); } @J2ktIncompatible @GwtIncompatible // propagate - public void testPropagate_noneDeclared_errorThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsError(); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - }; - - // Expect the error to propagate as-is - assertThrows(SomeError.class, () -> sample.noneDeclared()); + public void testPropagate_noneDeclared_error() { + assertThrows(SomeError.class, () -> propagate(new SomeError())); } @J2ktIncompatible @GwtIncompatible // propagate - public void testPropagate_noneDeclared_checkedThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsChecked(); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - }; - - // Expect the undeclared exception to have been chained inside another - RuntimeException expected = assertThrows(RuntimeException.class, () -> sample.noneDeclared()); + public void testPropagate_noneDeclared_checked() { + RuntimeException expected = + assertThrows(RuntimeException.class, () -> propagate(new SomeCheckedException())); assertThat(expected).hasCauseThat().isInstanceOf(SomeCheckedException.class); } @@ -419,89 +218,28 @@ public void testThrowIfInstanceOf_checkedSubclass() { () -> throwIfInstanceOf(new SomeCheckedException() {}, SomeCheckedException.class)); } - @J2ktIncompatible - @GwtIncompatible // propagate]IfInstanceOf - public void testPropagateIfInstanceOf_noneThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - Throwables.propagateIfInstanceOf(t, SomeCheckedException.class); - throw Throwables.propagate(t); - } - } - }; - - // Expect no exception to be thrown - sample.oneDeclared(); - } - @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf - public void testPropagateIfInstanceOf_declaredThrown() { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsChecked(); - } catch (Throwable t) { - Throwables.propagateIfInstanceOf(t, SomeCheckedException.class); - throw Throwables.propagate(t); - } - } - }; - - // Expect declared exception to be thrown as-is - assertThrows(SomeCheckedException.class, () -> sample.oneDeclared()); + public void testPropagateIfInstanceOf_checkedSame() { + assertThrows( + SomeCheckedException.class, + () -> propagateIfInstanceOf(new SomeCheckedException(), SomeCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf - public void testPropagateIfInstanceOf_uncheckedThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - Throwables.propagateIfInstanceOf(t, SomeCheckedException.class); - throw Throwables.propagate(t); - } - } - }; - - // Expect unchecked exception to be thrown as-is - assertThrows(SomeUncheckedException.class, () -> sample.oneDeclared()); + public void testPropagateIfInstanceOf_unchecked() throws SomeCheckedException { + propagateIfInstanceOf(new SomeUncheckedException(), SomeCheckedException.class); } @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf - public void testPropagateIfInstanceOf_undeclaredThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsOtherChecked(); - } catch (Throwable t) { - Throwables.propagateIfInstanceOf(t, SomeCheckedException.class); - throw Throwables.propagate(t); - } - } - }; - - // Expect undeclared exception wrapped by RuntimeException to be thrown - RuntimeException expected = assertThrows(RuntimeException.class, () -> sample.oneDeclared()); - assertThat(expected).hasCauseThat().isInstanceOf(SomeOtherCheckedException.class); + public void testPropagateIfInstanceOf_checkedDifferent() throws SomeCheckedException { + propagateIfInstanceOf(new SomeOtherCheckedException(), SomeCheckedException.class); } @GwtIncompatible // throwIfInstanceOf - public void testThrowIfInstanceOf_null() throws SomeCheckedException { + public void testThrowIfInstanceOf_null() { assertThrows( NullPointerException.class, () -> throwIfInstanceOf(null, SomeCheckedException.class)); } @@ -509,82 +247,33 @@ public void testThrowIfInstanceOf_null() throws SomeCheckedException { @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf public void testPropageIfInstanceOf_null() throws SomeCheckedException { - Throwables.propagateIfInstanceOf(null, SomeCheckedException.class); + propagateIfInstanceOf(null, SomeCheckedException.class); } public void testGetRootCause_noCause() { SomeCheckedException exception = new SomeCheckedException(); - assertSame(exception, Throwables.getRootCause(exception)); + assertSame(exception, getRootCause(exception)); } public void testGetRootCause_singleWrapped() { SomeCheckedException cause = new SomeCheckedException(); SomeChainingException exception = new SomeChainingException(cause); - assertSame(cause, Throwables.getRootCause(exception)); + assertSame(cause, getRootCause(exception)); } public void testGetRootCause_doubleWrapped() { SomeCheckedException cause = new SomeCheckedException(); SomeChainingException exception = new SomeChainingException(new SomeChainingException(cause)); - assertSame(cause, Throwables.getRootCause(exception)); + assertSame(cause, getRootCause(exception)); } public void testGetRootCause_loop() { Exception cause = new Exception(); Exception exception = new Exception(cause); cause.initCause(exception); - try { - Throwables.getRootCause(cause); - fail("Should have throw IAE"); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasCauseThat().isSameInstanceAs(cause); - } - } - - private static class SomeError extends Error {} - - private static class SomeCheckedException extends Exception {} - - private static class SomeOtherCheckedException extends Exception {} - - private static class SomeUncheckedException extends RuntimeException {} - - private static class SomeUndeclaredCheckedException extends Exception {} - - private static class SomeChainingException extends RuntimeException { - public SomeChainingException(Throwable cause) { - super(cause); - } - } - - static class Sample { - void noneDeclared() {} - - void oneDeclared() throws SomeCheckedException {} - - void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException {} - } - - static void methodThatDoesntThrowAnything() {} - - static void methodThatThrowsError() { - throw new SomeError(); - } - - static void methodThatThrowsUnchecked() { - throw new SomeUncheckedException(); - } - - static void methodThatThrowsChecked() throws SomeCheckedException { - throw new SomeCheckedException(); - } - - static void methodThatThrowsOtherChecked() throws SomeOtherCheckedException { - throw new SomeOtherCheckedException(); - } - - static void methodThatThrowsUndeclaredChecked() throws SomeUndeclaredCheckedException { - throw new SomeUndeclaredCheckedException(); + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> getRootCause(cause)); + assertThat(expected).hasCauseThat().isSameInstanceAs(cause); } @J2ktIncompatible // Format does not match @@ -612,50 +301,38 @@ public void testGetCausalChain() { RuntimeException re = new RuntimeException(iae); IllegalStateException ex = new IllegalStateException(re); - assertEquals(asList(ex, re, iae, sue), Throwables.getCausalChain(ex)); - assertSame(sue, Iterables.getOnlyElement(Throwables.getCausalChain(sue))); + assertThat(getCausalChain(ex)).containsExactly(ex, re, iae, sue).inOrder(); + assertSame(sue, Iterables.getOnlyElement(getCausalChain(sue))); - List causes = Throwables.getCausalChain(ex); - try { - causes.add(new RuntimeException()); - fail("List should be unmodifiable"); - } catch (UnsupportedOperationException expected) { - } + List causes = getCausalChain(ex); + assertThrows(UnsupportedOperationException.class, () -> causes.add(new RuntimeException())); } public void testGetCasualChainNull() { - try { - Throwables.getCausalChain(null); - fail("Should have throw NPE"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> getCausalChain(null)); } public void testGetCasualChainLoop() { Exception cause = new Exception(); Exception exception = new Exception(cause); cause.initCause(exception); - try { - Throwables.getCausalChain(cause); - fail("Should have throw IAE"); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasCauseThat().isSameInstanceAs(cause); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> getCausalChain(cause)); + assertThat(expected).hasCauseThat().isSameInstanceAs(cause); } - @GwtIncompatible // Throwables.getCauseAs(Throwable, Class) + @GwtIncompatible // getCauseAs(Throwable, Class) public void testGetCauseAs() { SomeCheckedException cause = new SomeCheckedException(); SomeChainingException thrown = new SomeChainingException(cause); assertThat(thrown).hasCauseThat().isSameInstanceAs(cause); - assertThat(Throwables.getCauseAs(thrown, SomeCheckedException.class)).isSameInstanceAs(cause); - assertThat(Throwables.getCauseAs(thrown, Exception.class)).isSameInstanceAs(cause); + assertThat(getCauseAs(thrown, SomeCheckedException.class)).isSameInstanceAs(cause); + assertThat(getCauseAs(thrown, Exception.class)).isSameInstanceAs(cause); ClassCastException expected = assertThrows( - ClassCastException.class, - () -> Throwables.getCauseAs(thrown, IllegalStateException.class)); + ClassCastException.class, () -> getCauseAs(thrown, IllegalStateException.class)); assertThat(expected).hasCauseThat().isSameInstanceAs(thrown); } diff --git a/android/guava-tests/test/com/google/common/base/ToStringHelperTest.java b/android/guava-tests/test/com/google/common/base/ToStringHelperTest.java index 05b6d7002914..ae1d5a20a380 100644 --- a/android/guava-tests/test/com/google/common/base/ToStringHelperTest.java +++ b/android/guava-tests/test/com/google/common/base/ToStringHelperTest.java @@ -16,6 +16,8 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.ImmutableMap; @@ -221,11 +223,7 @@ public void testToStringLenient_complexFields() { public void testToString_addWithNullName() { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(new TestClass()); - try { - helper.add(null, "Hello"); - fail("No exception was thrown."); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> helper.add(null, "Hello")); } @GwtIncompatible // Class names are obfuscated in GWT diff --git a/android/guava-tests/test/com/google/common/base/VerifyTest.java b/android/guava-tests/test/com/google/common/base/VerifyTest.java index 36465ea30fa8..6257c5eb7faa 100644 --- a/android/guava-tests/test/com/google/common/base/VerifyTest.java +++ b/android/guava-tests/test/com/google/common/base/VerifyTest.java @@ -14,6 +14,7 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.base.Verify.verify; import static com.google.common.base.Verify.verifyNotNull; import static com.google.common.truth.Truth.assertThat; @@ -32,11 +33,7 @@ public void testVerify_simple_success() { } public void testVerify_simple_failure() { - try { - verify(false); - fail(); - } catch (VerifyException expected) { - } + assertThrows(VerifyException.class, () -> verify(false)); } public void testVerify_simpleMessage_success() { @@ -44,12 +41,8 @@ public void testVerify_simpleMessage_success() { } public void testVerify_simpleMessage_failure() { - try { - verify(false, "message"); - fail(); - } catch (VerifyException expected) { - assertThat(expected).hasMessageThat().isEqualTo("message"); - } + VerifyException expected = assertThrows(VerifyException.class, () -> verify(false, "message")); + assertThat(expected).hasMessageThat().isEqualTo("message"); } public void testVerify_complexMessage_success() { @@ -57,12 +50,8 @@ public void testVerify_complexMessage_success() { } public void testVerify_complexMessage_failure() { - try { - verify(false, FORMAT, 5); - fail(); - } catch (VerifyException expected) { - checkMessage(expected); - } + VerifyException expected = assertThrows(VerifyException.class, () -> verify(false, FORMAT, 5)); + checkMessage(expected); } private static final String NON_NULL_STRING = "foo"; @@ -73,11 +62,7 @@ public void testVerifyNotNull_simple_success() { } public void testVerifyNotNull_simple_failure() { - try { - verifyNotNull(null); - fail(); - } catch (VerifyException expected) { - } + assertThrows(VerifyException.class, () -> verifyNotNull(null)); } public void testVerifyNotNull_complexMessage_success() { @@ -86,12 +71,9 @@ public void testVerifyNotNull_complexMessage_success() { } public void testVerifyNotNull_simpleMessage_failure() { - try { - verifyNotNull(null, FORMAT, 5); - fail(); - } catch (VerifyException expected) { - checkMessage(expected); - } + VerifyException expected = + assertThrows(VerifyException.class, () -> verifyNotNull(null, FORMAT, 5)); + checkMessage(expected); } @J2ktIncompatible diff --git a/guava-tests/test/com/google/common/base/AbstractIteratorTest.java b/guava-tests/test/com/google/common/base/AbstractIteratorTest.java index b1cdae52efca..7dc3d0274017 100644 --- a/guava-tests/test/com/google/common/base/AbstractIteratorTest.java +++ b/guava-tests/test/com/google/common/base/AbstractIteratorTest.java @@ -16,9 +16,13 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; +import com.google.common.base.TestExceptions.SomeCheckedException; +import com.google.common.base.TestExceptions.SomeUncheckedException; import com.google.common.testing.GcFinalization; import java.lang.ref.WeakReference; import java.util.Iterator; @@ -70,11 +74,7 @@ public Integer computeNext() { // Make sure computeNext() doesn't get invoked again assertFalse(iter.hasNext()); - try { - iter.next(); - fail("no exception thrown"); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, iter::next); } public void testSneakyThrow() throws Exception { @@ -95,21 +95,9 @@ public Integer computeNext() { }; // The first time, the sneakily-thrown exception comes out - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (Exception e) { - if (!(e instanceof SomeCheckedException)) { - throw e; - } - } - + assertThrows(SomeCheckedException.class, iter::hasNext); // But the second time, AbstractIterator itself throws an ISE - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, iter::hasNext); } public void testException() { @@ -123,12 +111,8 @@ public Integer computeNext() { }; // It should pass through untouched - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (SomeUncheckedException e) { - assertSame(exception, e); - } + SomeUncheckedException e = assertThrows(SomeUncheckedException.class, iter::hasNext); + assertSame(exception, e); } public void testExceptionAfterEndOfData() { @@ -140,11 +124,7 @@ public Integer computeNext() { throw new SomeUncheckedException(); } }; - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (SomeUncheckedException expected) { - } + assertThrows(SomeUncheckedException.class, iter::hasNext); } public void testCantRemove() { @@ -164,11 +144,7 @@ public Integer computeNext() { assertEquals(0, (int) iter.next()); - try { - iter.remove(); - fail("No exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, iter::remove); } @@ -196,11 +172,7 @@ protected Integer computeNext() { throw new AssertionError(); } }; - try { - iter.hasNext(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, iter::hasNext); } // Technically we should test other reentrant scenarios (4 combinations of @@ -217,8 +189,4 @@ void throwIt(Throwable t) throws T { } new SneakyThrower().throwIt(t); } - - private static class SomeCheckedException extends Exception {} - - private static class SomeUncheckedException extends RuntimeException {} } diff --git a/guava-tests/test/com/google/common/base/AsciiTest.java b/guava-tests/test/com/google/common/base/AsciiTest.java index 9e6b0e41ab86..3017289c5077 100644 --- a/guava-tests/test/com/google/common/base/AsciiTest.java +++ b/guava-tests/test/com/google/common/base/AsciiTest.java @@ -16,6 +16,8 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import junit.framework.TestCase; @@ -98,29 +100,13 @@ public void testTruncate() { } public void testTruncateIllegalArguments() { - try { - Ascii.truncate("foobar", 2, "..."); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ascii.truncate("foobar", 2, "...")); - try { - Ascii.truncate("foobar", 8, "1234567890"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ascii.truncate("foobar", 8, "1234567890")); - try { - Ascii.truncate("foobar", -1, "..."); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ascii.truncate("foobar", -1, "...")); - try { - Ascii.truncate("foobar", -1, ""); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ascii.truncate("foobar", -1, "")); } public void testEqualsIgnoreCase() { diff --git a/guava-tests/test/com/google/common/base/FunctionsTest.java b/guava-tests/test/com/google/common/base/FunctionsTest.java index 6e70ea710b6a..1241200daafa 100644 --- a/guava-tests/test/com/google/common/base/FunctionsTest.java +++ b/guava-tests/test/com/google/common/base/FunctionsTest.java @@ -16,6 +16,8 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -70,11 +72,7 @@ public String toString() { return "I'm a string"; } })); - try { - Functions.toStringFunction().apply(null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Functions.toStringFunction().apply(null)); } @J2ktIncompatible @@ -101,11 +99,7 @@ public void testForMapWithoutDefault() { assertEquals(3, function.apply("Three").intValue()); assertNull(function.apply("Null")); - try { - function.apply("Two"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> function.apply("Two")); new EqualsTester() .addEqualityGroup(function, Functions.forMap(map)) @@ -225,17 +219,9 @@ public void testComposition() { Functions.compose(integerToSpanish, japaneseToInteger); assertEquals("Uno", japaneseToSpanish.apply("Ichi")); - try { - japaneseToSpanish.apply("Ni"); - fail(); - } catch (IllegalArgumentException e) { - } + assertThrows(IllegalArgumentException.class, () -> japaneseToSpanish.apply("Ni")); assertEquals("Tres", japaneseToSpanish.apply("San")); - try { - japaneseToSpanish.apply("Shi"); - fail(); - } catch (IllegalArgumentException e) { - } + assertThrows(IllegalArgumentException.class, () -> japaneseToSpanish.apply("Shi")); new EqualsTester() .addEqualityGroup(japaneseToSpanish, Functions.compose(integerToSpanish, japaneseToInteger)) diff --git a/guava-tests/test/com/google/common/base/JoinerTest.java b/guava-tests/test/com/google/common/base/JoinerTest.java index babc3d6e5b80..36cba68cf32a 100644 --- a/guava-tests/test/com/google/common/base/JoinerTest.java +++ b/guava-tests/test/com/google/common/base/JoinerTest.java @@ -16,19 +16,19 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Joiner.MapJoiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.testing.NullPointerTester; import java.io.IOException; import java.util.Arrays; -import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @@ -60,33 +60,18 @@ public class JoinerTest extends TestCase { private static final Iterable<@Nullable Integer> ITERABLE_FOUR_NULLS = Arrays.asList((Integer) null, null, null, null); + @SuppressWarnings("JoinIterableIterator") // explicitly testing iterator overload, too public void testNoSpecialNullBehavior() { checkNoOutput(J, ITERABLE_); checkResult(J, ITERABLE_1, "1"); checkResult(J, ITERABLE_12, "1-2"); checkResult(J, ITERABLE_123, "1-2-3"); - try { - J.join(ITERABLE_NULL); - fail(); - } catch (NullPointerException expected) { - } - try { - J.join(ITERABLE_1_NULL_2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> J.join(ITERABLE_NULL)); + assertThrows(NullPointerException.class, () -> J.join(ITERABLE_1_NULL_2)); - try { - J.join(ITERABLE_NULL.iterator()); - fail(); - } catch (NullPointerException expected) { - } - try { - J.join(ITERABLE_1_NULL_2.iterator()); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> J.join(ITERABLE_NULL.iterator())); + assertThrows(NullPointerException.class, () -> J.join(ITERABLE_1_NULL_2.iterator())); } public void testOnCharOverride() { @@ -218,29 +203,17 @@ private static void checkResult(Joiner joiner, Iterable parts, String e public void test_useForNull_skipNulls() { Joiner j = Joiner.on("x").useForNull("y"); - try { - j = j.skipNulls(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, j::skipNulls); } public void test_skipNulls_useForNull() { Joiner j = Joiner.on("x").skipNulls(); - try { - j = j.useForNull("y"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> j.useForNull("y")); } public void test_useForNull_twice() { Joiner j = Joiner.on("x").useForNull("y"); - try { - j = j.useForNull("y"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> j.useForNull("y")); } public void testMap() { @@ -252,11 +225,7 @@ public void testMap() { mapWithNulls.put("a", null); mapWithNulls.put(null, "b"); - try { - j.join(mapWithNulls); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> j.join(mapWithNulls)); assertEquals("a:00;00:b", j.useForNull("00").join(mapWithNulls)); @@ -279,17 +248,9 @@ public void testEntries() { mapWithNulls.put(null, "b"); Set> entriesWithNulls = mapWithNulls.entrySet(); - try { - j.join(entriesWithNulls); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> j.join(entriesWithNulls)); - try { - j.join(entriesWithNulls.iterator()); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> j.join(entriesWithNulls.iterator())); assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls)); assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls.iterator())); @@ -305,11 +266,7 @@ public void testEntries() { public void test_skipNulls_onMap() { Joiner j = Joiner.on(",").skipNulls(); - try { - j.withKeyValueSeparator("/"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> j.withKeyValueSeparator("/")); } private static class DontStringMeBro implements CharSequence { @@ -334,36 +291,6 @@ public String toString() { } } - // Don't do this. - private static class IterableIterator implements Iterable, Iterator { - private static final ImmutableSet INTEGERS = ImmutableSet.of(1, 2, 3, 4); - private final Iterator iterator; - - public IterableIterator() { - this.iterator = iterator(); - } - - @Override - public Iterator iterator() { - return INTEGERS.iterator(); - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public Integer next() { - return iterator.next(); - } - - @Override - public void remove() { - iterator.remove(); - } - } - @GwtIncompatible // StringBuilder.append in GWT invokes Object.toString(), unlike the JRE version. public void testDontConvertCharSequenceToString() { assertEquals("foo,foo", Joiner.on(",").join(new DontStringMeBro(), new DontStringMeBro())); diff --git a/guava-tests/test/com/google/common/base/MoreObjectsTest.java b/guava-tests/test/com/google/common/base/MoreObjectsTest.java index 8c6d809d114d..9b3bbadd1b7d 100644 --- a/guava-tests/test/com/google/common/base/MoreObjectsTest.java +++ b/guava-tests/test/com/google/common/base/MoreObjectsTest.java @@ -16,6 +16,8 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -40,11 +42,7 @@ public void testFirstNonNull_withNonNull() { } public void testFirstNonNull_throwsNullPointerException() { - try { - MoreObjects.firstNonNull(null, null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> MoreObjects.firstNonNull(null, null)); } // ToStringHelper's tests are in ToStringHelperTest diff --git a/guava-tests/test/com/google/common/base/OptionalTest.java b/guava-tests/test/com/google/common/base/OptionalTest.java index 5239726f3e42..ec197f5c2b82 100644 --- a/guava-tests/test/com/google/common/base/OptionalTest.java +++ b/guava-tests/test/com/google/common/base/OptionalTest.java @@ -16,6 +16,7 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.truth.Truth.assertThat; @@ -40,6 +41,7 @@ @ElementTypesAreNonnullByDefault @GwtCompatible(emulated = true) public final class OptionalTest extends TestCase { + @SuppressWarnings("NullOptional") public void testToJavaUtil_static() { assertNull(Optional.toJavaUtil(null)); assertEquals(java.util.Optional.empty(), Optional.toJavaUtil(Optional.absent())); @@ -51,6 +53,7 @@ public void testToJavaUtil_instance() { assertEquals(java.util.Optional.of("abc"), Optional.of("abc").toJavaUtil()); } + @SuppressWarnings("NullOptional") public void testFromJavaUtil() { assertNull(Optional.fromJavaUtil(null)); assertEquals(Optional.absent(), Optional.fromJavaUtil(java.util.Optional.empty())); @@ -67,11 +70,7 @@ public void testOf() { } public void testOf_null() { - try { - Optional.of(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Optional.of(null)); } public void testFromNullable() { @@ -95,11 +94,7 @@ public void testIsPresent_yes() { public void testGet_absent() { Optional optional = Optional.absent(); - try { - optional.get(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, optional::get); } public void testGet_present() { @@ -127,11 +122,7 @@ public void testOr_supplier_absent() { public void testOr_nullSupplier_absent() { Supplier nullSupplier = (Supplier) Suppliers.<@Nullable Object>ofInstance(null); Optional absentOptional = Optional.absent(); - try { - absentOptional.or(nullSupplier); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> absentOptional.or(nullSupplier)); } @SuppressWarnings("OptionalOfRedundantMethod") // Unit tests for Optional @@ -169,20 +160,12 @@ public void testAsSet_absent() { public void testAsSet_presentIsImmutable() { Set presentAsSet = Optional.of("a").asSet(); - try { - presentAsSet.add("b"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> presentAsSet.add("b")); } public void testAsSet_absentIsImmutable() { Set absentAsSet = Optional.absent().asSet(); - try { - absentAsSet.add("foo"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> absentAsSet.add("foo")); } public void testTransform_absent() { @@ -199,34 +182,11 @@ public void testTransform_presentToString() { } public void testTransform_present_functionReturnsNull() { - try { - Optional unused = - Optional.of("a") - .transform( - (Function) - new Function() { - @Override - public @Nullable String apply(String input) { - return null; - } - }); - fail("Should throw if Function returns null."); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Optional.of("a").transform(input -> null)); } public void testTransform_absent_functionReturnsNull() { - assertEquals( - Optional.absent(), - Optional.absent() - .transform( - (Function) - new Function() { - @Override - public @Nullable Object apply(Object input) { - return null; - } - })); + assertEquals(Optional.absent(), Optional.absent().transform(input -> null)); } public void testEqualsAndHashCode() { diff --git a/guava-tests/test/com/google/common/base/PreconditionsTest.java b/guava-tests/test/com/google/common/base/PreconditionsTest.java index 61776d1f84ed..71845c8e5892 100644 --- a/guava-tests/test/com/google/common/base/PreconditionsTest.java +++ b/guava-tests/test/com/google/common/base/PreconditionsTest.java @@ -16,8 +16,14 @@ package com.google.common.base; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkElementIndex; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkPositionIndex; +import static com.google.common.base.Preconditions.checkPositionIndexes; +import static com.google.common.base.Preconditions.checkState; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -46,347 +52,248 @@ @GwtCompatible(emulated = true) public class PreconditionsTest extends TestCase { public void testCheckArgument_simple_success() { - Preconditions.checkArgument(true); + checkArgument(true); } public void testCheckArgument_simple_failure() { - try { - Preconditions.checkArgument(false); - fail("no exception thrown"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> checkArgument(false)); } public void testCheckArgument_simpleMessage_success() { - Preconditions.checkArgument(true, IGNORE_ME); + checkArgument(true, IGNORE_ME); } public void testCheckArgument_simpleMessage_failure() { - try { - Preconditions.checkArgument(false, new Message()); - fail("no exception thrown"); - } catch (IllegalArgumentException expected) { - verifySimpleMessage(expected); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> checkArgument(false, new Message())); + verifySimpleMessage(expected); } public void testCheckArgument_nullMessage_failure() { - try { - Preconditions.checkArgument(false, null); - fail("no exception thrown"); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("null"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> checkArgument(false, null)); + assertThat(expected).hasMessageThat().isEqualTo("null"); } public void testCheckArgument_nullMessageWithArgs_failure() { - try { - Preconditions.checkArgument(false, null, "b", "d"); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("null [b, d]"); - } + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> checkArgument(false, null, "b", "d")); + assertThat(e).hasMessageThat().isEqualTo("null [b, d]"); } public void testCheckArgument_nullArgs_failure() { - try { - Preconditions.checkArgument(false, "A %s C %s E", null, null); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A null C null E"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, () -> checkArgument(false, "A %s C %s E", null, null)); + assertThat(e).hasMessageThat().isEqualTo("A null C null E"); } public void testCheckArgument_notEnoughArgs_failure() { - try { - Preconditions.checkArgument(false, "A %s C %s E", "b"); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A b C %s E"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, () -> checkArgument(false, "A %s C %s E", "b")); + assertThat(e).hasMessageThat().isEqualTo("A b C %s E"); } public void testCheckArgument_tooManyArgs_failure() { - try { - Preconditions.checkArgument(false, "A %s C %s E", "b", "d", "f"); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A b C d E [f]"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, + () -> checkArgument(false, "A %s C %s E", "b", "d", "f")); + assertThat(e).hasMessageThat().isEqualTo("A b C d E [f]"); } public void testCheckArgument_singleNullArg_failure() { - try { - Preconditions.checkArgument(false, "A %s C", (Object) null); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A null C"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, () -> checkArgument(false, "A %s C", (Object) null)); + assertThat(e).hasMessageThat().isEqualTo("A null C"); } @J2ktIncompatible // TODO(b/319404022): Allow passing null array as varargs public void testCheckArgument_singleNullArray_failure() { - try { - Preconditions.checkArgument(false, "A %s C", (Object[]) null); - fail("no exception thrown"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("A (Object[])null C"); - } + IllegalArgumentException e = + assertThrows( + IllegalArgumentException.class, () -> checkArgument(false, "A %s C", (Object[]) null)); + assertThat(e).hasMessageThat().isEqualTo("A (Object[])null C"); } public void testCheckArgument_complexMessage_success() { - Preconditions.checkArgument(true, "%s", IGNORE_ME); + checkArgument(true, "%s", IGNORE_ME); } public void testCheckArgument_complexMessage_failure() { - try { - Preconditions.checkArgument(false, FORMAT, 5); - fail("no exception thrown"); - } catch (IllegalArgumentException expected) { - verifyComplexMessage(expected); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> checkArgument(false, FORMAT, 5)); + verifyComplexMessage(expected); } public void testCheckState_simple_success() { - Preconditions.checkState(true); + checkState(true); } public void testCheckState_simple_failure() { - try { - Preconditions.checkState(false); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> checkState(false)); } public void testCheckState_simpleMessage_success() { - Preconditions.checkState(true, IGNORE_ME); + checkState(true, IGNORE_ME); } public void testCheckState_simpleMessage_failure() { - try { - Preconditions.checkState(false, new Message()); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - verifySimpleMessage(expected); - } + IllegalStateException expected = + assertThrows(IllegalStateException.class, () -> checkState(false, new Message())); + verifySimpleMessage(expected); } public void testCheckState_nullMessage_failure() { - try { - Preconditions.checkState(false, null); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - assertThat(expected).hasMessageThat().isEqualTo("null"); - } + IllegalStateException expected = + assertThrows(IllegalStateException.class, () -> checkState(false, null)); + assertThat(expected).hasMessageThat().isEqualTo("null"); } public void testCheckState_complexMessage_success() { - Preconditions.checkState(true, "%s", IGNORE_ME); + checkState(true, "%s", IGNORE_ME); } public void testCheckState_complexMessage_failure() { - try { - Preconditions.checkState(false, FORMAT, 5); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - verifyComplexMessage(expected); - } + IllegalStateException expected = + assertThrows(IllegalStateException.class, () -> checkState(false, FORMAT, 5)); + verifyComplexMessage(expected); } private static final String NON_NULL_STRING = "foo"; public void testCheckNotNull_simple_success() { - String result = Preconditions.checkNotNull(NON_NULL_STRING); + String result = checkNotNull(NON_NULL_STRING); assertSame(NON_NULL_STRING, result); } public void testCheckNotNull_simple_failure() { - try { - Preconditions.checkNotNull(null); - fail("no exception thrown"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> checkNotNull(null)); } public void testCheckNotNull_simpleMessage_success() { - String result = Preconditions.checkNotNull(NON_NULL_STRING, IGNORE_ME); + String result = checkNotNull(NON_NULL_STRING, IGNORE_ME); assertSame(NON_NULL_STRING, result); } public void testCheckNotNull_simpleMessage_failure() { - try { - Preconditions.checkNotNull(null, new Message()); - fail("no exception thrown"); - } catch (NullPointerException expected) { - verifySimpleMessage(expected); - } + NullPointerException expected = + assertThrows(NullPointerException.class, () -> checkNotNull(null, new Message())); + verifySimpleMessage(expected); } public void testCheckNotNull_complexMessage_success() { - String result = Preconditions.checkNotNull(NON_NULL_STRING, "%s", IGNORE_ME); + String result = checkNotNull(NON_NULL_STRING, "%s", IGNORE_ME); assertSame(NON_NULL_STRING, result); } public void testCheckNotNull_complexMessage_failure() { - try { - Preconditions.checkNotNull(null, FORMAT, 5); - fail("no exception thrown"); - } catch (NullPointerException expected) { - verifyComplexMessage(expected); - } + NullPointerException expected = + assertThrows(NullPointerException.class, () -> checkNotNull(null, FORMAT, 5)); + verifyComplexMessage(expected); } public void testCheckElementIndex_ok() { - assertEquals(0, Preconditions.checkElementIndex(0, 1)); - assertEquals(0, Preconditions.checkElementIndex(0, 2)); - assertEquals(1, Preconditions.checkElementIndex(1, 2)); + assertEquals(0, checkElementIndex(0, 1)); + assertEquals(0, checkElementIndex(0, 2)); + assertEquals(1, checkElementIndex(1, 2)); } public void testCheckElementIndex_badSize() { - try { - Preconditions.checkElementIndex(1, -1); - fail(); - } catch (IllegalArgumentException expected) { - // don't care what the message text is, as this is an invalid usage of - // the Preconditions class, unlike all the other exceptions it throws - } + assertThrows(IllegalArgumentException.class, () -> checkElementIndex(1, -1)); } public void testCheckElementIndex_negative() { - try { - Preconditions.checkElementIndex(-1, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("index (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkElementIndex(-1, 1)); + assertThat(expected).hasMessageThat().isEqualTo("index (-1) must not be negative"); } public void testCheckElementIndex_tooHigh() { - try { - Preconditions.checkElementIndex(1, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("index (1) must be less than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkElementIndex(1, 1)); + assertThat(expected).hasMessageThat().isEqualTo("index (1) must be less than size (1)"); } public void testCheckElementIndex_withDesc_negative() { - try { - Preconditions.checkElementIndex(-1, 1, "foo"); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("foo (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkElementIndex(-1, 1, "foo")); + assertThat(expected).hasMessageThat().isEqualTo("foo (-1) must not be negative"); } public void testCheckElementIndex_withDesc_tooHigh() { - try { - Preconditions.checkElementIndex(1, 1, "foo"); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("foo (1) must be less than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkElementIndex(1, 1, "foo")); + assertThat(expected).hasMessageThat().isEqualTo("foo (1) must be less than size (1)"); } public void testCheckPositionIndex_ok() { - assertEquals(0, Preconditions.checkPositionIndex(0, 0)); - assertEquals(0, Preconditions.checkPositionIndex(0, 1)); - assertEquals(1, Preconditions.checkPositionIndex(1, 1)); + assertEquals(0, checkPositionIndex(0, 0)); + assertEquals(0, checkPositionIndex(0, 1)); + assertEquals(1, checkPositionIndex(1, 1)); } public void testCheckPositionIndex_badSize() { - try { - Preconditions.checkPositionIndex(1, -1); - fail(); - } catch (IllegalArgumentException expected) { - // don't care what the message text is, as this is an invalid usage of - // the Preconditions class, unlike all the other exceptions it throws - } + assertThrows(IllegalArgumentException.class, () -> checkPositionIndex(1, -1)); } public void testCheckPositionIndex_negative() { - try { - Preconditions.checkPositionIndex(-1, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("index (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndex(-1, 1)); + assertThat(expected).hasMessageThat().isEqualTo("index (-1) must not be negative"); } public void testCheckPositionIndex_tooHigh() { - try { - Preconditions.checkPositionIndex(2, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("index (2) must not be greater than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndex(2, 1)); + assertThat(expected).hasMessageThat().isEqualTo("index (2) must not be greater than size (1)"); } public void testCheckPositionIndex_withDesc_negative() { - try { - Preconditions.checkPositionIndex(-1, 1, "foo"); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("foo (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndex(-1, 1, "foo")); + assertThat(expected).hasMessageThat().isEqualTo("foo (-1) must not be negative"); } public void testCheckPositionIndex_withDesc_tooHigh() { - try { - Preconditions.checkPositionIndex(2, 1, "foo"); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("foo (2) must not be greater than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndex(2, 1, "foo")); + assertThat(expected).hasMessageThat().isEqualTo("foo (2) must not be greater than size (1)"); } public void testCheckPositionIndexes_ok() { - Preconditions.checkPositionIndexes(0, 0, 0); - Preconditions.checkPositionIndexes(0, 0, 1); - Preconditions.checkPositionIndexes(0, 1, 1); - Preconditions.checkPositionIndexes(1, 1, 1); + checkPositionIndexes(0, 0, 0); + checkPositionIndexes(0, 0, 1); + checkPositionIndexes(0, 1, 1); + checkPositionIndexes(1, 1, 1); } public void testCheckPositionIndexes_badSize() { - try { - Preconditions.checkPositionIndexes(1, 1, -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> checkPositionIndexes(1, 1, -1)); } public void testCheckPositionIndex_startNegative() { - try { - Preconditions.checkPositionIndexes(-1, 1, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected).hasMessageThat().isEqualTo("start index (-1) must not be negative"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndexes(-1, 1, 1)); + assertThat(expected).hasMessageThat().isEqualTo("start index (-1) must not be negative"); } public void testCheckPositionIndexes_endTooHigh() { - try { - Preconditions.checkPositionIndexes(0, 2, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("end index (2) must not be greater than size (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndexes(0, 2, 1)); + assertThat(expected) + .hasMessageThat() + .isEqualTo("end index (2) must not be greater than size (1)"); } public void testCheckPositionIndexes_reversed() { - try { - Preconditions.checkPositionIndexes(1, 0, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("end index (0) must not be less than start index (1)"); - } + IndexOutOfBoundsException expected = + assertThrows(IndexOutOfBoundsException.class, () -> checkPositionIndexes(1, 0, 1)); + assertThat(expected) + .hasMessageThat() + .isEqualTo("end index (0) must not be less than start index (1)"); } @GwtIncompatible("Reflection") @@ -528,20 +435,20 @@ public void overloadSelection() { int anInt = 1; // With a boxed predicate, no overloads can be selected in phase 1 // ambiguous without the call to .booleanValue to unbox the Boolean - Preconditions.checkState(boxedBoolean.booleanValue(), "", 1); + checkState(boxedBoolean.booleanValue(), "", 1); // ambiguous without the cast to Object because the boxed predicate prevents any overload from // being selected in phase 1 - Preconditions.checkState(boxedBoolean, "", (Object) boxedLong); + checkState(boxedBoolean, "", (Object) boxedLong); // ternaries introduce their own problems. because of the ternary (which requires a boxing // operation) no overload can be selected in phase 1. and in phase 2 it is ambiguous since it // matches with the second parameter being boxed and without it being boxed. The cast to Object // avoids this. - Preconditions.checkState(aBoolean, "", aBoolean ? "" : anInt, (Object) anInt); + checkState(aBoolean, "", aBoolean ? "" : anInt, (Object) anInt); // ambiguous without the .booleanValue() call since the boxing forces us into phase 2 resolution short s = 2; - Preconditions.checkState(boxedBoolean.booleanValue(), "", s); + checkState(boxedBoolean.booleanValue(), "", s); } @J2ktIncompatible diff --git a/guava-tests/test/com/google/common/base/ReflectionFreeAssertThrows.java b/guava-tests/test/com/google/common/base/ReflectionFreeAssertThrows.java new file mode 100644 index 000000000000..7996a8b26fdf --- /dev/null +++ b/guava-tests/test/com/google/common/base/ReflectionFreeAssertThrows.java @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2024 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.base; + +import com.google.common.annotations.GwtCompatible; +import com.google.common.annotations.GwtIncompatible; +import com.google.common.annotations.J2ktIncompatible; +import com.google.common.base.TestExceptions.SomeCheckedException; +import com.google.common.base.TestExceptions.SomeError; +import com.google.common.base.TestExceptions.SomeOtherCheckedException; +import com.google.common.base.TestExceptions.SomeUncheckedException; +import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.ExecutionError; +import com.google.common.util.concurrent.UncheckedExecutionException; +import com.google.errorprone.annotations.CanIgnoreReturnValue; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.UnsupportedCharsetException; +import java.util.ConcurrentModificationException; +import java.util.NoSuchElementException; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import junit.framework.AssertionFailedError; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Replacements for JUnit's {@code assertThrows} that work under GWT/J2CL. */ +@GwtCompatible(emulated = true) +@ElementTypesAreNonnullByDefault +final class ReflectionFreeAssertThrows { + interface ThrowingRunnable { + void run() throws Throwable; + } + + interface ThrowingSupplier { + @Nullable Object get() throws Throwable; + } + + @CanIgnoreReturnValue + static T assertThrows( + Class expectedThrowable, ThrowingSupplier supplier) { + return doAssertThrows(expectedThrowable, supplier, /* userPassedSupplier= */ true); + } + + @CanIgnoreReturnValue + static T assertThrows( + Class expectedThrowable, ThrowingRunnable runnable) { + return doAssertThrows( + expectedThrowable, + () -> { + runnable.run(); + return null; + }, + /* userPassedSupplier= */ false); + } + + private static T doAssertThrows( + Class expectedThrowable, ThrowingSupplier supplier, boolean userPassedSupplier) { + Predicate predicate = INSTANCE_OF.get(expectedThrowable); + if (predicate == null) { + throw new IllegalArgumentException( + expectedThrowable + + " is not yet supported by ReflectionFreeAssertThrows. Add an entry for it in the" + + " map in that class."); + } + Object result; + try { + result = supplier.get(); + } catch (Throwable t) { + if (predicate.apply(t)) { + // We are careful to set up INSTANCE_OF to match each Predicate to its target Class. + @SuppressWarnings("unchecked") + T caught = (T) t; + return caught; + } + throw new AssertionError( + "expected to throw " + expectedThrowable.getSimpleName() + " but threw " + t, t); + } + if (userPassedSupplier) { + throw new AssertionError( + "expected to throw " + + expectedThrowable.getSimpleName() + + " but returned result: " + + result); + } else { + throw new AssertionError("expected to throw " + expectedThrowable.getSimpleName()); + } + } + + private enum PlatformSpecificExceptionBatch { + PLATFORM { + @GwtIncompatible + @J2ktIncompatible + @Override + // returns the types available in "normal" environments + ImmutableMap, Predicate> exceptions() { + return ImmutableMap.of( + InvocationTargetException.class, + e -> e instanceof InvocationTargetException, + StackOverflowError.class, + e -> e instanceof StackOverflowError); + } + }; + + // used under GWT, etc., since the override of this method does not exist there + ImmutableMap, Predicate> exceptions() { + return ImmutableMap.of(); + } + } + + private static final ImmutableMap, Predicate> INSTANCE_OF = + ImmutableMap., Predicate>builder() + .put(ArithmeticException.class, e -> e instanceof ArithmeticException) + .put( + ArrayIndexOutOfBoundsException.class, + e -> e instanceof ArrayIndexOutOfBoundsException) + .put(ArrayStoreException.class, e -> e instanceof ArrayStoreException) + .put(AssertionFailedError.class, e -> e instanceof AssertionFailedError) + .put(CancellationException.class, e -> e instanceof CancellationException) + .put(ClassCastException.class, e -> e instanceof ClassCastException) + .put( + ConcurrentModificationException.class, + e -> e instanceof ConcurrentModificationException) + .put(ExecutionError.class, e -> e instanceof ExecutionError) + .put(ExecutionException.class, e -> e instanceof ExecutionException) + .put(IllegalArgumentException.class, e -> e instanceof IllegalArgumentException) + .put(IllegalStateException.class, e -> e instanceof IllegalStateException) + .put(IndexOutOfBoundsException.class, e -> e instanceof IndexOutOfBoundsException) + .put(NoSuchElementException.class, e -> e instanceof NoSuchElementException) + .put(NullPointerException.class, e -> e instanceof NullPointerException) + .put(NumberFormatException.class, e -> e instanceof NumberFormatException) + .put(RuntimeException.class, e -> e instanceof RuntimeException) + .put(SomeCheckedException.class, e -> e instanceof SomeCheckedException) + .put(SomeError.class, e -> e instanceof SomeError) + .put(SomeOtherCheckedException.class, e -> e instanceof SomeOtherCheckedException) + .put(SomeUncheckedException.class, e -> e instanceof SomeUncheckedException) + .put(TimeoutException.class, e -> e instanceof TimeoutException) + .put(UncheckedExecutionException.class, e -> e instanceof UncheckedExecutionException) + .put(UnsupportedCharsetException.class, e -> e instanceof UnsupportedCharsetException) + .put(UnsupportedOperationException.class, e -> e instanceof UnsupportedOperationException) + .put(VerifyException.class, e -> e instanceof VerifyException) + .putAll(PlatformSpecificExceptionBatch.PLATFORM.exceptions()) + .buildOrThrow(); + + private ReflectionFreeAssertThrows() {} +} diff --git a/guava-tests/test/com/google/common/base/SplitterTest.java b/guava-tests/test/com/google/common/base/SplitterTest.java index 9800eab4776d..71a37a5f08e0 100644 --- a/guava-tests/test/com/google/common/base/SplitterTest.java +++ b/guava-tests/test/com/google/common/base/SplitterTest.java @@ -16,9 +16,9 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -42,11 +42,7 @@ public class SplitterTest extends TestCase { private static final Splitter COMMA_SPLITTER = Splitter.on(','); public void testSplitNullString() { - try { - COMMA_SPLITTER.split(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> COMMA_SPLITTER.split(null)); } public void testCharacterSimpleSplit() { @@ -261,11 +257,7 @@ public void testStringSplitWithDelimiterSubstringInValue() { } public void testStringSplitWithEmptyString() { - try { - Splitter.on(""); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Splitter.on("")); } public void testStringSplitOnEmptyString() { @@ -568,19 +560,11 @@ public void testFixedLengthSplitIntoChars() { } public void testFixedLengthSplitZeroChunkLen() { - try { - Splitter.fixedLength(0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Splitter.fixedLength(0)); } public void testFixedLengthSplitNegativeChunkLen() { - try { - Splitter.fixedLength(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Splitter.fixedLength(-1)); } public void testLimitLarge() { @@ -668,11 +652,7 @@ public void testLimitExtraSeparatorsTrim1EmptyOmit() { } public void testInvalidZeroLimit() { - try { - COMMA_SPLITTER.limit(0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> COMMA_SPLITTER.limit(0)); } @J2ktIncompatible @@ -756,19 +736,13 @@ public void testMapSplitter_multiCharacterSeparator() { } public void testMapSplitter_emptySeparator() { - try { - COMMA_SPLITTER.withKeyValueSeparator(""); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> COMMA_SPLITTER.withKeyValueSeparator("")); } public void testMapSplitter_malformedEntry() { - try { - COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,b,c=2"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,b,c=2")); } /** @@ -776,11 +750,9 @@ public void testMapSplitter_malformedEntry() { * be changed? */ public void testMapSplitter_extraValueDelimiter() { - try { - COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,c=2="); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,c=2=")); } public void testMapSplitter_orderedResults() { @@ -800,11 +772,9 @@ public void testMapSplitter_orderedResults() { } public void testMapSplitter_duplicateKeys() { - try { - COMMA_SPLITTER.withKeyValueSeparator(":").split("a:1,b:2,a:3"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> COMMA_SPLITTER.withKeyValueSeparator(":").split("a:1,b:2,a:3")); } public void testMapSplitter_varyingTrimLevels() { diff --git a/guava-tests/test/com/google/common/base/StopwatchTest.java b/guava-tests/test/com/google/common/base/StopwatchTest.java index 99e4998d6865..abe0f438fb2a 100644 --- a/guava-tests/test/com/google/common/base/StopwatchTest.java +++ b/guava-tests/test/com/google/common/base/StopwatchTest.java @@ -16,6 +16,7 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; @@ -59,11 +60,7 @@ public void testStart() { public void testStart_whileRunning() { stopwatch.start(); - try { - stopwatch.start(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, stopwatch::start); assertTrue(stopwatch.isRunning()); } @@ -74,22 +71,14 @@ public void testStop() { } public void testStop_new() { - try { - stopwatch.stop(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, stopwatch::stop); assertFalse(stopwatch.isRunning()); } public void testStop_alreadyStopped() { stopwatch.start(); stopwatch.stop(); - try { - stopwatch.stop(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, stopwatch::stop); assertFalse(stopwatch.isRunning()); } diff --git a/guava-tests/test/com/google/common/base/StringsTest.java b/guava-tests/test/com/google/common/base/StringsTest.java index 72e441ef8729..494f321c208d 100644 --- a/guava-tests/test/com/google/common/base/StringsTest.java +++ b/guava-tests/test/com/google/common/base/StringsTest.java @@ -16,6 +16,7 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -72,11 +73,7 @@ public void testPadStart_negativeMinLength() { // TODO: could remove if we got NPT working in GWT somehow public void testPadStart_null() { - try { - Strings.padStart(null, 5, '0'); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Strings.padStart(null, 5, '0')); } public void testPadEnd_noPadding() { @@ -99,15 +96,11 @@ public void testPadEnd_negativeMinLength() { assertSame("x", Strings.padEnd("x", -1, '-')); } - // TODO: could remove if we got NPT working in GWT somehow public void testPadEnd_null() { - try { - Strings.padEnd(null, 5, '0'); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Strings.padEnd(null, 5, '0')); } + @SuppressWarnings("InlineMeInliner") // test of method that doesn't just delegate public void testRepeat() { String input = "20"; assertEquals("", Strings.repeat(input, 0)); @@ -121,28 +114,17 @@ public void testRepeat() { assertEquals(2 * i, Strings.repeat(input, i).length()); } - try { - Strings.repeat("x", -1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - // Massive string - Strings.repeat("12345678", (1 << 30) + 3); - fail(); - } catch (ArrayIndexOutOfBoundsException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Strings.repeat("x", -1)); + assertThrows( + ArrayIndexOutOfBoundsException.class, () -> Strings.repeat("12345678", (1 << 30) + 3)); } - // TODO: could remove if we got NPT working in GWT somehow + @SuppressWarnings("InlineMeInliner") // test of method that doesn't just delegate public void testRepeat_null() { - try { - Strings.repeat(null, 5); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Strings.repeat(null, 5)); } + @SuppressWarnings("UnnecessaryStringBuilder") // We want to test a non-String CharSequence public void testCommonPrefix() { assertEquals("", Strings.commonPrefix("", "")); assertEquals("", Strings.commonPrefix("abc", "")); @@ -152,7 +134,7 @@ public void testCommonPrefix() { assertEquals("", Strings.commonPrefix("xyz", "abcxyz")); assertEquals("a", Strings.commonPrefix("abc", "aaaaa")); assertEquals("aa", Strings.commonPrefix("aa", "aaaaa")); - assertEquals("abc", Strings.commonPrefix(new StringBuffer("abcdef"), "abcxyz")); + assertEquals("abc", Strings.commonPrefix(new StringBuilder("abcdef"), "abcxyz")); // Identical valid surrogate pairs. assertEquals( @@ -172,6 +154,7 @@ public void testCommonPrefix() { assertEquals("\uD8AB", Strings.commonPrefix("\uD8AB", "\uD8AB")); } + @SuppressWarnings("UnnecessaryStringBuilder") // We want to test a non-String CharSequence public void testCommonSuffix() { assertEquals("", Strings.commonSuffix("", "")); assertEquals("", Strings.commonSuffix("abc", "")); @@ -181,7 +164,7 @@ public void testCommonSuffix() { assertEquals("", Strings.commonSuffix("xyz", "xyzabc")); assertEquals("c", Strings.commonSuffix("abc", "ccccc")); assertEquals("aa", Strings.commonSuffix("aa", "aaaaa")); - assertEquals("abc", Strings.commonSuffix(new StringBuffer("xyzabc"), "xxxabc")); + assertEquals("abc", Strings.commonSuffix(new StringBuilder("xyzabc"), "xxxabc")); // Identical valid surrogate pairs. assertEquals( diff --git a/guava-tests/test/com/google/common/base/SuppliersTest.java b/guava-tests/test/com/google/common/base/SuppliersTest.java index 1954c164c076..8b0313ed62f4 100644 --- a/guava-tests/test/com/google/common/base/SuppliersTest.java +++ b/guava-tests/test/com/google/common/base/SuppliersTest.java @@ -16,9 +16,9 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -243,35 +243,26 @@ public void testMemoizeWithExpiration_duration() throws InterruptedException { @SuppressWarnings("DoNotCall") public void testMemoizeWithExpiration_longTimeUnitNegative() throws InterruptedException { - try { - Supplier unused = Suppliers.memoizeWithExpiration(() -> "", 0, TimeUnit.MILLISECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Suppliers.memoizeWithExpiration(() -> "", 0, TimeUnit.MILLISECONDS)); - try { - Supplier unused = - Suppliers.memoizeWithExpiration(() -> "", -1, TimeUnit.MILLISECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Suppliers.memoizeWithExpiration(() -> "", -1, TimeUnit.MILLISECONDS)); } @SuppressWarnings("Java7ApiChecker") // test of Java 8+ API @J2ktIncompatible // Duration @GwtIncompatible // Duration public void testMemoizeWithExpiration_durationNegative() throws InterruptedException { - try { - Supplier unused = Suppliers.memoizeWithExpiration(() -> "", Duration.ZERO); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Suppliers.memoizeWithExpiration(() -> "", Duration.ZERO)); - try { - Supplier unused = Suppliers.memoizeWithExpiration(() -> "", Duration.ofMillis(-1)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Suppliers.memoizeWithExpiration(() -> "", Duration.ofMillis(-1))); } @J2ktIncompatible @@ -393,6 +384,7 @@ int waitingThreads() { } @Override + @SuppressWarnings("ThreadPriorityCheck") // doing our best to test for races public Boolean get() { // Check that this method is called exactly once, by the first // thread to synchronize. @@ -438,6 +430,7 @@ public void run() { @J2ktIncompatible @GwtIncompatible // Thread + @SuppressWarnings("ThreadPriorityCheck") // doing our best to test for races public void testSynchronizedSupplierThreadSafe() throws InterruptedException { final Supplier nonThreadSafe = new Supplier() { diff --git a/guava-tests/test/com/google/common/base/TestExceptions.java b/guava-tests/test/com/google/common/base/TestExceptions.java new file mode 100644 index 000000000000..35152703f673 --- /dev/null +++ b/guava-tests/test/com/google/common/base/TestExceptions.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2007 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.base; + + +import com.google.common.annotations.GwtCompatible; + +/** Exception classes for use in tests. */ +@GwtCompatible +final class TestExceptions { + static class SomeError extends Error {} + + static class SomeCheckedException extends Exception {} + + static class SomeOtherCheckedException extends Exception {} + + static class YetAnotherCheckedException extends Exception {} + + static class SomeUncheckedException extends RuntimeException {} + + static class SomeChainingException extends RuntimeException { + public SomeChainingException(Throwable cause) { + super(cause); + } + } + + private TestExceptions() {} +} diff --git a/guava-tests/test/com/google/common/base/ThrowablesTest.java b/guava-tests/test/com/google/common/base/ThrowablesTest.java index 1e11f8d3dc67..78fd4affa5d4 100644 --- a/guava-tests/test/com/google/common/base/ThrowablesTest.java +++ b/guava-tests/test/com/google/common/base/ThrowablesTest.java @@ -16,20 +16,31 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION; +import static com.google.common.base.Throwables.getCausalChain; +import static com.google.common.base.Throwables.getCauseAs; +import static com.google.common.base.Throwables.getRootCause; import static com.google.common.base.Throwables.getStackTraceAsString; import static com.google.common.base.Throwables.lazyStackTrace; import static com.google.common.base.Throwables.lazyStackTraceIsLazy; +import static com.google.common.base.Throwables.propagate; +import static com.google.common.base.Throwables.propagateIfInstanceOf; +import static com.google.common.base.Throwables.propagateIfPossible; import static com.google.common.base.Throwables.throwIfInstanceOf; import static com.google.common.base.Throwables.throwIfUnchecked; import static com.google.common.truth.Truth.assertThat; -import static java.util.Arrays.asList; import static java.util.regex.Pattern.quote; -import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; +import com.google.common.base.TestExceptions.SomeChainingException; +import com.google.common.base.TestExceptions.SomeCheckedException; +import com.google.common.base.TestExceptions.SomeError; +import com.google.common.base.TestExceptions.SomeOtherCheckedException; +import com.google.common.base.TestExceptions.SomeUncheckedException; +import com.google.common.base.TestExceptions.YetAnotherCheckedException; import com.google.common.collect.Iterables; import com.google.common.primitives.Ints; import com.google.common.testing.NullPointerTester; @@ -42,21 +53,15 @@ * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) +@SuppressWarnings("deprecation") // tests of numerous deprecated methods public class ThrowablesTest extends TestCase { public void testThrowIfUnchecked_unchecked() { - try { - throwIfUnchecked(new SomeUncheckedException()); - fail(); - } catch (SomeUncheckedException expected) { - } + assertThrows( + SomeUncheckedException.class, () -> throwIfUnchecked(new SomeUncheckedException())); } public void testThrowIfUnchecked_error() { - try { - throwIfUnchecked(new SomeError()); - fail(); - } catch (SomeError expected) { - } + assertThrows(SomeError.class, () -> throwIfUnchecked(new SomeError())); } @SuppressWarnings("ThrowIfUncheckedKnownChecked") @@ -66,332 +71,126 @@ public void testThrowIfUnchecked_checked() { @J2ktIncompatible @GwtIncompatible // propagateIfPossible - public void testPropagateIfPossible_noneDeclared_noneThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t); - throw new SomeChainingException(t); - } - } - }; - - // Expect no exception to be thrown - sample.noneDeclared(); - } - - @J2ktIncompatible - @GwtIncompatible // propagateIfPossible - public void testPropagateIfPossible_noneDeclared_uncheckedThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t); - throw new SomeChainingException(t); - } - } - }; - - // Expect the unchecked exception to propagate as-is - assertThrows(SomeUncheckedException.class, () -> sample.noneDeclared()); + public void testPropagateIfPossible_noneDeclared_unchecked() { + assertThrows( + SomeUncheckedException.class, () -> propagateIfPossible(new SomeUncheckedException())); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible - public void testPropagateIfPossible_noneDeclared_undeclaredThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsUndeclaredChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t); - throw new SomeChainingException(t); - } - } - }; - - // Expect the undeclared exception to have been chained inside another - assertThrows(SomeChainingException.class, () -> sample.noneDeclared()); + @SuppressWarnings("ThrowIfUncheckedKnownChecked") + public void testPropagateIfPossible_noneDeclared_checked() { + propagateIfPossible(new SomeCheckedException()); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class) - public void testPropagateIfPossible_oneDeclared_noneThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - // yes, this block is never reached, but for purposes of illustration - // we're keeping it the same in each test - Throwables.propagateIfPossible(t, SomeCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect no exception to be thrown - sample.oneDeclared(); + public void testPropagateIfPossible_oneDeclared_unchecked() { + assertThrows( + SomeUncheckedException.class, + () -> propagateIfPossible(new SomeUncheckedException(), SomeCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class) - public void testPropagateIfPossible_oneDeclared_uncheckedThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t, SomeCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the unchecked exception to propagate as-is - assertThrows(SomeUncheckedException.class, () -> sample.oneDeclared()); + public void testPropagateIfPossible_oneDeclared_checkedSame() { + assertThrows( + SomeCheckedException.class, + () -> propagateIfPossible(new SomeCheckedException(), SomeCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class) - public void testPropagateIfPossible_oneDeclared_checkedThrown() { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t, SomeCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the checked exception to propagate as-is - assertThrows(SomeCheckedException.class, () -> sample.oneDeclared()); + public void testPropagateIfPossible_oneDeclared_checkedDifferent() throws SomeCheckedException { + propagateIfPossible(new SomeOtherCheckedException(), SomeCheckedException.class); } @J2ktIncompatible - @GwtIncompatible // propagateIfPossible(Throwable, Class) - public void testPropagateIfPossible_oneDeclared_undeclaredThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsUndeclaredChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible(t, SomeCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the undeclared exception to have been chained inside another - assertThrows(SomeChainingException.class, () -> sample.oneDeclared()); + @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) + public void testPropagateIfPossible_twoDeclared_unchecked() { + assertThrows( + SomeUncheckedException.class, + () -> + propagateIfPossible( + new SomeUncheckedException(), + SomeCheckedException.class, + SomeOtherCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropagateIfPossible_twoDeclared_noneThrown() - throws SomeCheckedException, SomeOtherCheckedException { - Sample sample = - new Sample() { - @Override - public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - Throwables.propagateIfPossible( - t, SomeCheckedException.class, SomeOtherCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect no exception to be thrown - sample.twoDeclared(); + public void testPropagateIfPossible_twoDeclared_firstSame() { + assertThrows( + SomeCheckedException.class, + () -> + propagateIfPossible( + new SomeCheckedException(), + SomeCheckedException.class, + SomeOtherCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropagateIfPossible_twoDeclared_uncheckedThrown() - throws SomeCheckedException, SomeOtherCheckedException { - Sample sample = - new Sample() { - @Override - public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible( - t, SomeCheckedException.class, SomeOtherCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the unchecked exception to propagate as-is - assertThrows(SomeUncheckedException.class, () -> sample.twoDeclared()); + public void testPropagateIfPossible_twoDeclared_secondSame() { + assertThrows( + SomeOtherCheckedException.class, + () -> + propagateIfPossible( + new SomeOtherCheckedException(), + SomeCheckedException.class, + SomeOtherCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropagateIfPossible_twoDeclared_checkedThrown() throws SomeOtherCheckedException { - Sample sample = - new Sample() { - @Override - public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException { - try { - methodThatThrowsChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible( - t, SomeCheckedException.class, SomeOtherCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the checked exception to propagate as-is - assertThrows(SomeCheckedException.class, () -> sample.twoDeclared()); + public void testPropagateIfPossible_twoDeclared_neitherSame() + throws SomeCheckedException, SomeOtherCheckedException { + propagateIfPossible( + new YetAnotherCheckedException(), + SomeCheckedException.class, + SomeOtherCheckedException.class); } - @J2ktIncompatible - @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropagateIfPossible_twoDeclared_otherCheckedThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException { - try { - methodThatThrowsOtherChecked(); - } catch (Throwable t) { - Throwables.propagateIfPossible( - t, SomeCheckedException.class, SomeOtherCheckedException.class); - throw new SomeChainingException(t); - } - } - }; - - // Expect the checked exception to propagate as-is - assertThrows(SomeOtherCheckedException.class, () -> sample.twoDeclared()); - } - - public void testThrowIfUnchecked_null() throws SomeCheckedException { - try { - throwIfUnchecked(null); - fail(); - } catch (NullPointerException expected) { - } + public void testThrowIfUnchecked_null() { + assertThrows(NullPointerException.class, () -> throwIfUnchecked(null)); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible - public void testPropageIfPossible_null() throws SomeCheckedException { - Throwables.propagateIfPossible(null); + public void testPropageIfPossible_null() { + propagateIfPossible(null); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class) public void testPropageIfPossible_oneDeclared_null() throws SomeCheckedException { - Throwables.propagateIfPossible(null, SomeCheckedException.class); + propagateIfPossible(null, SomeCheckedException.class); } @J2ktIncompatible @GwtIncompatible // propagateIfPossible(Throwable, Class, Class) - public void testPropageIfPossible_twoDeclared_null() throws SomeCheckedException { - Throwables.propagateIfPossible(null, SomeCheckedException.class, SomeUncheckedException.class); - } - - @J2ktIncompatible - @GwtIncompatible // propagate - public void testPropagate_noneDeclared_noneThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - }; - - // Expect no exception to be thrown - sample.noneDeclared(); + public void testPropageIfPossible_twoDeclared_null() + throws SomeCheckedException, SomeOtherCheckedException { + propagateIfPossible(null, SomeCheckedException.class, SomeOtherCheckedException.class); } @J2ktIncompatible @GwtIncompatible // propagate - public void testPropagate_noneDeclared_uncheckedThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - }; - - // Expect the unchecked exception to propagate as-is - assertThrows(SomeUncheckedException.class, () -> sample.noneDeclared()); + public void testPropagate_noneDeclared_unchecked() { + assertThrows(SomeUncheckedException.class, () -> propagate(new SomeUncheckedException())); } @J2ktIncompatible @GwtIncompatible // propagate - public void testPropagate_noneDeclared_errorThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsError(); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - }; - - // Expect the error to propagate as-is - assertThrows(SomeError.class, () -> sample.noneDeclared()); + public void testPropagate_noneDeclared_error() { + assertThrows(SomeError.class, () -> propagate(new SomeError())); } @J2ktIncompatible @GwtIncompatible // propagate - public void testPropagate_noneDeclared_checkedThrown() { - Sample sample = - new Sample() { - @Override - public void noneDeclared() { - try { - methodThatThrowsChecked(); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - }; - - // Expect the undeclared exception to have been chained inside another - RuntimeException expected = assertThrows(RuntimeException.class, () -> sample.noneDeclared()); + public void testPropagate_noneDeclared_checked() { + RuntimeException expected = + assertThrows(RuntimeException.class, () -> propagate(new SomeCheckedException())); assertThat(expected).hasCauseThat().isInstanceOf(SomeCheckedException.class); } @@ -419,89 +218,28 @@ public void testThrowIfInstanceOf_checkedSubclass() { () -> throwIfInstanceOf(new SomeCheckedException() {}, SomeCheckedException.class)); } - @J2ktIncompatible - @GwtIncompatible // propagate]IfInstanceOf - public void testPropagateIfInstanceOf_noneThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatDoesntThrowAnything(); - } catch (Throwable t) { - Throwables.propagateIfInstanceOf(t, SomeCheckedException.class); - throw Throwables.propagate(t); - } - } - }; - - // Expect no exception to be thrown - sample.oneDeclared(); - } - @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf - public void testPropagateIfInstanceOf_declaredThrown() { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsChecked(); - } catch (Throwable t) { - Throwables.propagateIfInstanceOf(t, SomeCheckedException.class); - throw Throwables.propagate(t); - } - } - }; - - // Expect declared exception to be thrown as-is - assertThrows(SomeCheckedException.class, () -> sample.oneDeclared()); + public void testPropagateIfInstanceOf_checkedSame() { + assertThrows( + SomeCheckedException.class, + () -> propagateIfInstanceOf(new SomeCheckedException(), SomeCheckedException.class)); } @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf - public void testPropagateIfInstanceOf_uncheckedThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsUnchecked(); - } catch (Throwable t) { - Throwables.propagateIfInstanceOf(t, SomeCheckedException.class); - throw Throwables.propagate(t); - } - } - }; - - // Expect unchecked exception to be thrown as-is - assertThrows(SomeUncheckedException.class, () -> sample.oneDeclared()); + public void testPropagateIfInstanceOf_unchecked() throws SomeCheckedException { + propagateIfInstanceOf(new SomeUncheckedException(), SomeCheckedException.class); } @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf - public void testPropagateIfInstanceOf_undeclaredThrown() throws SomeCheckedException { - Sample sample = - new Sample() { - @Override - public void oneDeclared() throws SomeCheckedException { - try { - methodThatThrowsOtherChecked(); - } catch (Throwable t) { - Throwables.propagateIfInstanceOf(t, SomeCheckedException.class); - throw Throwables.propagate(t); - } - } - }; - - // Expect undeclared exception wrapped by RuntimeException to be thrown - RuntimeException expected = assertThrows(RuntimeException.class, () -> sample.oneDeclared()); - assertThat(expected).hasCauseThat().isInstanceOf(SomeOtherCheckedException.class); + public void testPropagateIfInstanceOf_checkedDifferent() throws SomeCheckedException { + propagateIfInstanceOf(new SomeOtherCheckedException(), SomeCheckedException.class); } @GwtIncompatible // throwIfInstanceOf - public void testThrowIfInstanceOf_null() throws SomeCheckedException { + public void testThrowIfInstanceOf_null() { assertThrows( NullPointerException.class, () -> throwIfInstanceOf(null, SomeCheckedException.class)); } @@ -509,82 +247,33 @@ public void testThrowIfInstanceOf_null() throws SomeCheckedException { @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf public void testPropageIfInstanceOf_null() throws SomeCheckedException { - Throwables.propagateIfInstanceOf(null, SomeCheckedException.class); + propagateIfInstanceOf(null, SomeCheckedException.class); } public void testGetRootCause_noCause() { SomeCheckedException exception = new SomeCheckedException(); - assertSame(exception, Throwables.getRootCause(exception)); + assertSame(exception, getRootCause(exception)); } public void testGetRootCause_singleWrapped() { SomeCheckedException cause = new SomeCheckedException(); SomeChainingException exception = new SomeChainingException(cause); - assertSame(cause, Throwables.getRootCause(exception)); + assertSame(cause, getRootCause(exception)); } public void testGetRootCause_doubleWrapped() { SomeCheckedException cause = new SomeCheckedException(); SomeChainingException exception = new SomeChainingException(new SomeChainingException(cause)); - assertSame(cause, Throwables.getRootCause(exception)); + assertSame(cause, getRootCause(exception)); } public void testGetRootCause_loop() { Exception cause = new Exception(); Exception exception = new Exception(cause); cause.initCause(exception); - try { - Throwables.getRootCause(cause); - fail("Should have throw IAE"); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasCauseThat().isSameInstanceAs(cause); - } - } - - private static class SomeError extends Error {} - - private static class SomeCheckedException extends Exception {} - - private static class SomeOtherCheckedException extends Exception {} - - private static class SomeUncheckedException extends RuntimeException {} - - private static class SomeUndeclaredCheckedException extends Exception {} - - private static class SomeChainingException extends RuntimeException { - public SomeChainingException(Throwable cause) { - super(cause); - } - } - - static class Sample { - void noneDeclared() {} - - void oneDeclared() throws SomeCheckedException {} - - void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException {} - } - - static void methodThatDoesntThrowAnything() {} - - static void methodThatThrowsError() { - throw new SomeError(); - } - - static void methodThatThrowsUnchecked() { - throw new SomeUncheckedException(); - } - - static void methodThatThrowsChecked() throws SomeCheckedException { - throw new SomeCheckedException(); - } - - static void methodThatThrowsOtherChecked() throws SomeOtherCheckedException { - throw new SomeOtherCheckedException(); - } - - static void methodThatThrowsUndeclaredChecked() throws SomeUndeclaredCheckedException { - throw new SomeUndeclaredCheckedException(); + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> getRootCause(cause)); + assertThat(expected).hasCauseThat().isSameInstanceAs(cause); } @J2ktIncompatible // Format does not match @@ -612,50 +301,38 @@ public void testGetCausalChain() { RuntimeException re = new RuntimeException(iae); IllegalStateException ex = new IllegalStateException(re); - assertEquals(asList(ex, re, iae, sue), Throwables.getCausalChain(ex)); - assertSame(sue, Iterables.getOnlyElement(Throwables.getCausalChain(sue))); + assertThat(getCausalChain(ex)).containsExactly(ex, re, iae, sue).inOrder(); + assertSame(sue, Iterables.getOnlyElement(getCausalChain(sue))); - List causes = Throwables.getCausalChain(ex); - try { - causes.add(new RuntimeException()); - fail("List should be unmodifiable"); - } catch (UnsupportedOperationException expected) { - } + List causes = getCausalChain(ex); + assertThrows(UnsupportedOperationException.class, () -> causes.add(new RuntimeException())); } public void testGetCasualChainNull() { - try { - Throwables.getCausalChain(null); - fail("Should have throw NPE"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> getCausalChain(null)); } public void testGetCasualChainLoop() { Exception cause = new Exception(); Exception exception = new Exception(cause); cause.initCause(exception); - try { - Throwables.getCausalChain(cause); - fail("Should have throw IAE"); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasCauseThat().isSameInstanceAs(cause); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> getCausalChain(cause)); + assertThat(expected).hasCauseThat().isSameInstanceAs(cause); } - @GwtIncompatible // Throwables.getCauseAs(Throwable, Class) + @GwtIncompatible // getCauseAs(Throwable, Class) public void testGetCauseAs() { SomeCheckedException cause = new SomeCheckedException(); SomeChainingException thrown = new SomeChainingException(cause); assertThat(thrown).hasCauseThat().isSameInstanceAs(cause); - assertThat(Throwables.getCauseAs(thrown, SomeCheckedException.class)).isSameInstanceAs(cause); - assertThat(Throwables.getCauseAs(thrown, Exception.class)).isSameInstanceAs(cause); + assertThat(getCauseAs(thrown, SomeCheckedException.class)).isSameInstanceAs(cause); + assertThat(getCauseAs(thrown, Exception.class)).isSameInstanceAs(cause); ClassCastException expected = assertThrows( - ClassCastException.class, - () -> Throwables.getCauseAs(thrown, IllegalStateException.class)); + ClassCastException.class, () -> getCauseAs(thrown, IllegalStateException.class)); assertThat(expected).hasCauseThat().isSameInstanceAs(thrown); } diff --git a/guava-tests/test/com/google/common/base/ToStringHelperTest.java b/guava-tests/test/com/google/common/base/ToStringHelperTest.java index 05b6d7002914..ae1d5a20a380 100644 --- a/guava-tests/test/com/google/common/base/ToStringHelperTest.java +++ b/guava-tests/test/com/google/common/base/ToStringHelperTest.java @@ -16,6 +16,8 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.ImmutableMap; @@ -221,11 +223,7 @@ public void testToStringLenient_complexFields() { public void testToString_addWithNullName() { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(new TestClass()); - try { - helper.add(null, "Hello"); - fail("No exception was thrown."); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> helper.add(null, "Hello")); } @GwtIncompatible // Class names are obfuscated in GWT diff --git a/guava-tests/test/com/google/common/base/VerifyTest.java b/guava-tests/test/com/google/common/base/VerifyTest.java index 36465ea30fa8..6257c5eb7faa 100644 --- a/guava-tests/test/com/google/common/base/VerifyTest.java +++ b/guava-tests/test/com/google/common/base/VerifyTest.java @@ -14,6 +14,7 @@ package com.google.common.base; +import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.base.Verify.verify; import static com.google.common.base.Verify.verifyNotNull; import static com.google.common.truth.Truth.assertThat; @@ -32,11 +33,7 @@ public void testVerify_simple_success() { } public void testVerify_simple_failure() { - try { - verify(false); - fail(); - } catch (VerifyException expected) { - } + assertThrows(VerifyException.class, () -> verify(false)); } public void testVerify_simpleMessage_success() { @@ -44,12 +41,8 @@ public void testVerify_simpleMessage_success() { } public void testVerify_simpleMessage_failure() { - try { - verify(false, "message"); - fail(); - } catch (VerifyException expected) { - assertThat(expected).hasMessageThat().isEqualTo("message"); - } + VerifyException expected = assertThrows(VerifyException.class, () -> verify(false, "message")); + assertThat(expected).hasMessageThat().isEqualTo("message"); } public void testVerify_complexMessage_success() { @@ -57,12 +50,8 @@ public void testVerify_complexMessage_success() { } public void testVerify_complexMessage_failure() { - try { - verify(false, FORMAT, 5); - fail(); - } catch (VerifyException expected) { - checkMessage(expected); - } + VerifyException expected = assertThrows(VerifyException.class, () -> verify(false, FORMAT, 5)); + checkMessage(expected); } private static final String NON_NULL_STRING = "foo"; @@ -73,11 +62,7 @@ public void testVerifyNotNull_simple_success() { } public void testVerifyNotNull_simple_failure() { - try { - verifyNotNull(null); - fail(); - } catch (VerifyException expected) { - } + assertThrows(VerifyException.class, () -> verifyNotNull(null)); } public void testVerifyNotNull_complexMessage_success() { @@ -86,12 +71,9 @@ public void testVerifyNotNull_complexMessage_success() { } public void testVerifyNotNull_simpleMessage_failure() { - try { - verifyNotNull(null, FORMAT, 5); - fail(); - } catch (VerifyException expected) { - checkMessage(expected); - } + VerifyException expected = + assertThrows(VerifyException.class, () -> verifyNotNull(null, FORMAT, 5)); + checkMessage(expected); } @J2ktIncompatible