diff --git a/android/guava-tests/test/com/google/common/collect/AbstractFilteredMapTest.java b/android/guava-tests/test/com/google/common/collect/AbstractFilteredMapTest.java index 068e1301e1e8..9dfa3fde21f6 100644 --- a/android/guava-tests/test/com/google/common/collect/AbstractFilteredMapTest.java +++ b/android/guava-tests/test/com/google/common/collect/AbstractFilteredMapTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.base.Predicate; import com.google.common.base.Predicates; @@ -42,11 +44,7 @@ public void testFilteredKeysIllegalPut() { filtered.put("b", 2); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); - try { - filtered.put("yyy", 3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> filtered.put("yyy", 3)); } public void testFilteredKeysIllegalPutAll() { @@ -56,11 +54,9 @@ public void testFilteredKeysIllegalPutAll() { filtered.put("b", 2); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); - try { - filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5))); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); } @@ -91,11 +87,7 @@ public void testFilteredValuesIllegalPut() { unfiltered.put("c", 5); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); - try { - filtered.put("yyy", 3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> filtered.put("yyy", 3)); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } @@ -107,11 +99,9 @@ public void testFilteredValuesIllegalPutAll() { unfiltered.put("c", 5); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); - try { - filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6))); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } @@ -123,11 +113,7 @@ public void testFilteredValuesIllegalSetValue() { assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); Entry entry = filtered.entrySet().iterator().next(); - try { - entry.setValue(5); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> entry.setValue(5)); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } @@ -158,11 +144,7 @@ public void testFilteredEntriesIllegalPut() { filtered.put("chicken", 7); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); - try { - filtered.put("cow", 7); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> filtered.put("cow", 7)); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); } @@ -177,11 +159,9 @@ public void testFilteredEntriesIllegalPutAll() { filtered.put("chicken", 7); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); - try { - filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7))); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); } diff --git a/android/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java b/android/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java index e87c42be38bc..c5716f94b159 100644 --- a/android/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java +++ b/android/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; @@ -132,20 +133,12 @@ public void testCopyOf_arrayOfOneElement() { } public void testCopyOf_nullArray() { - try { - copyOf((String[]) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> copyOf((String[]) null)); } public void testCopyOf_arrayContainingOnlyNull() { @Nullable String[] array = new @Nullable String[] {null}; - try { - copyOf((String[]) array); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> copyOf((String[]) array)); } public void testCopyOf_collection_empty() { @@ -178,11 +171,7 @@ public void testCopyOf_collection_general() { public void testCopyOf_collectionContainingNull() { Collection<@Nullable String> c = MinimalCollection.of("a", null, "b"); - try { - copyOf((Collection) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> copyOf((Collection) c)); } enum TestEnum { @@ -228,11 +217,7 @@ public void testCopyOf_iterator_general() { public void testCopyOf_iteratorContainingNull() { Iterator<@Nullable String> c = Iterators.forArray("a", null, "b"); - try { - copyOf((Iterator) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> copyOf((Iterator) c)); } private static class CountingIterable implements Iterable { @@ -398,76 +383,59 @@ public void testComplexBuilder() { abstract int getComplexBuilderSetLastElement(); public void testBuilderAddHandlesNullsCorrectly() { + { ImmutableSet.Builder builder = this.builder(); - try { - builder.add((String) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.add((String) null)); } - builder = this.builder(); - try { - builder.add((String[]) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add((String[]) null)); } - builder = this.builder(); - try { - builder.add("a", (String) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add("a", (String) null)); } - builder = this.builder(); - try { - builder.add("a", "b", (String) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add("a", "b", (String) null)); } - builder = this.builder(); - try { - builder.add("a", "b", "c", null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add("a", "b", "c", null)); } - builder = this.builder(); - try { - builder.add("a", "b", null, "c"); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add("a", "b", null, "c")); } } public void testBuilderAddAllHandlesNullsCorrectly() { + { ImmutableSet.Builder builder = this.builder(); - try { - builder.addAll((Iterable) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((Iterable) null)); } - try { - builder.addAll((Iterator) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.addAll((Iterator) null)); } - builder = this.builder(); + { + ImmutableSet.Builder builder = this.builder(); List<@Nullable String> listWithNulls = asList("a", null, "b"); - try { - builder.addAll((List) listWithNulls); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((List) listWithNulls)); } + { + ImmutableSet.Builder builder = this.builder(); Iterable<@Nullable String> iterableWithNulls = MinimalIterable.of("a", null, "b"); - try { - builder.addAll((Iterable) iterableWithNulls); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + assertThrows( + NullPointerException.class, () -> builder.addAll((Iterable) iterableWithNulls)); } } diff --git a/android/guava-tests/test/com/google/common/collect/AbstractImmutableTableTest.java b/android/guava-tests/test/com/google/common/collect/AbstractImmutableTableTest.java index 8edd14f5d847..45f877a17ecf 100644 --- a/android/guava-tests/test/com/google/common/collect/AbstractImmutableTableTest.java +++ b/android/guava-tests/test/com/google/common/collect/AbstractImmutableTableTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; @@ -32,45 +34,27 @@ public abstract class AbstractImmutableTableTest extends TestCase { public final void testClear() { for (Table testInstance : getTestInstances()) { - try { - testInstance.clear(); - fail(); - } catch (UnsupportedOperationException e) { - // success - } + assertThrows(UnsupportedOperationException.class, () -> testInstance.clear()); } } public final void testPut() { for (Table testInstance : getTestInstances()) { - try { - testInstance.put('a', 1, "blah"); - fail(); - } catch (UnsupportedOperationException e) { - // success - } + assertThrows(UnsupportedOperationException.class, () -> testInstance.put('a', 1, "blah")); } } public final void testPutAll() { for (Table testInstance : getTestInstances()) { - try { - testInstance.putAll(ImmutableTable.of('a', 1, "blah")); - fail(); - } catch (UnsupportedOperationException e) { - // success - } + assertThrows( + UnsupportedOperationException.class, + () -> testInstance.putAll(ImmutableTable.of('a', 1, "blah"))); } } public final void testRemove() { for (Table testInstance : getTestInstances()) { - try { - testInstance.remove('a', 1); - fail(); - } catch (UnsupportedOperationException e) { - // success - } + assertThrows(UnsupportedOperationException.class, () -> testInstance.remove('a', 1)); } } diff --git a/android/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java b/android/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java index 67ba8759d85d..1b6d6656483e 100644 --- a/android/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java +++ b/android/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java @@ -16,9 +16,13 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; +import com.google.common.collect.TestExceptions.SomeCheckedException; +import com.google.common.collect.TestExceptions.SomeUncheckedException; import com.google.common.testing.GcFinalization; import java.lang.ref.WeakReference; import java.util.Iterator; @@ -73,11 +77,7 @@ public void testDefaultBehaviorOfNextAndHasNext() { // 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 testDefaultBehaviorOfPeek() { @@ -113,29 +113,14 @@ public void testDefaultBehaviorOfPeek() { assertEquals(1, (int) iter.peek()); assertEquals(1, (int) iter.next()); - try { - iter.peek(); - fail("peek() should throw NoSuchElementException at end"); - } catch (NoSuchElementException expected) { - } - - try { - iter.peek(); - fail("peek() should continue to throw NoSuchElementException at end"); - } catch (NoSuchElementException expected) { - } - - try { - iter.next(); - fail("next() should throw NoSuchElementException as usual"); - } catch (NoSuchElementException expected) { - } - - try { - iter.peek(); - fail("peek() should still throw NoSuchElementException after next()"); - } catch (NoSuchElementException expected) { - } + /* + * We test peek() after various calls to make sure that one bad call doesn't interfere with its + * ability to throw the correct exception in the future. + */ + assertThrows(NoSuchElementException.class, iter::peek); + assertThrows(NoSuchElementException.class, iter::peek); + assertThrows(NoSuchElementException.class, iter::next); + assertThrows(NoSuchElementException.class, iter::peek); } @@ -170,17 +155,12 @@ public void testDefaultBehaviorOfPeekForEmptyIteration() { } }; - try { - empty.peek(); - fail("peek() should throw NoSuchElementException at end"); - } catch (NoSuchElementException expected) { - } - - try { - empty.peek(); - fail("peek() should continue to throw NoSuchElementException at end"); - } catch (NoSuchElementException expected) { - } + /* + * We test multiple calls to peek() to make sure that one bad call doesn't interfere with its + * ability to throw the correct exception in the future. + */ + assertThrows(NoSuchElementException.class, empty::peek); + assertThrows(NoSuchElementException.class, empty::peek); } public void testSneakyThrow() throws Exception { @@ -201,21 +181,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() { @@ -229,12 +197,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() { @@ -246,11 +210,7 @@ public Integer computeNext() { throw new SomeUncheckedException(); } }; - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (SomeUncheckedException expected) { - } + assertThrows(SomeUncheckedException.class, iter::hasNext); } @SuppressWarnings("DoNotCall") @@ -271,11 +231,7 @@ public Integer computeNext() { assertEquals(0, (int) iter.next()); - try { - iter.remove(); - fail("No exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, iter::remove); } public void testReentrantHasNext() { @@ -287,11 +243,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 (9 combinations of @@ -308,8 +260,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/collect/AbstractMapsTransformValuesTest.java b/android/guava-tests/test/com/google/common/collect/AbstractMapsTransformValuesTest.java index 67a47e67d355..218716ceb279 100644 --- a/android/guava-tests/test/com/google/common/collect/AbstractMapsTransformValuesTest.java +++ b/android/guava-tests/test/com/google/common/collect/AbstractMapsTransformValuesTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -87,23 +89,13 @@ public void testTransformIdentityFunctionEquality() { public void testTransformPutEntryIsUnsupported() { Map map = Maps.transformValues(ImmutableMap.of("a", 1), Functions.toStringFunction()); - try { - map.put("b", "2"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.put("b", "2")); - try { - map.putAll(ImmutableMap.of("b", "2")); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.putAll(ImmutableMap.of("b", "2"))); - try { - map.entrySet().iterator().next().setValue("one"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, + () -> map.entrySet().iterator().next().setValue("one")); } public void testTransformRemoveEntry() { diff --git a/android/guava-tests/test/com/google/common/collect/AbstractMultimapAsMapImplementsMapTest.java b/android/guava-tests/test/com/google/common/collect/AbstractMultimapAsMapImplementsMapTest.java index 06466c84df61..fcd6dc381023 100644 --- a/android/guava-tests/test/com/google/common/collect/AbstractMultimapAsMapImplementsMapTest.java +++ b/android/guava-tests/test/com/google/common/collect/AbstractMultimapAsMapImplementsMapTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MapInterfaceTest; import java.util.Collection; @@ -81,11 +83,7 @@ public void testRemove() { assertFalse(map.containsKey(keyToRemove)); assertEquals(initialSize - 1, map.size()); } else { - try { - map.remove(keyToRemove); - fail("Expected UnsupportedOperationException."); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.remove(keyToRemove)); } assertInvariants(map); } diff --git a/android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java b/android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java index 9b813c4bafa6..b1f64347ee53 100644 --- a/android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java +++ b/android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java @@ -16,11 +16,13 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; +import com.google.common.collect.TestExceptions.SomeUncheckedException; import com.google.common.collect.testing.IteratorTester; import java.util.Iterator; import java.util.NoSuchElementException; @@ -109,32 +111,16 @@ public Iterator iterator() { public void testEmpty() { Iterator empty = new EmptyAbstractSequentialIterator<>(); assertFalse(empty.hasNext()); - try { - empty.next(); - fail(); - } catch (NoSuchElementException expected) { - } - try { - empty.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(NoSuchElementException.class, empty::next); + assertThrows(UnsupportedOperationException.class, empty::remove); } public void testBroken() { Iterator broken = new BrokenAbstractSequentialIterator(); assertTrue(broken.hasNext()); // We can't retrieve even the known first element: - try { - broken.next(); - fail(); - } catch (MyException expected) { - } - try { - broken.next(); - fail(); - } catch (MyException expected) { - } + assertThrows(SomeUncheckedException.class, broken::next); + assertThrows(SomeUncheckedException.class, broken::next); } private static Iterator newDoubler(int first, final int last) { @@ -166,9 +152,7 @@ public BrokenAbstractSequentialIterator() { @Override protected Object computeNext(Object previous) { - throw new MyException(); + throw new SomeUncheckedException(); } } - - private static class MyException extends RuntimeException {} } diff --git a/android/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java b/android/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java index caa40a63a122..5eada001250c 100644 --- a/android/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java +++ b/android/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -159,11 +160,7 @@ public void testRow() { // This test assumes that the implementation does not support null keys. public void testRowNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); - try { - table.row(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.row(null)); } public void testColumn() { @@ -174,11 +171,7 @@ public void testColumn() { // This test assumes that the implementation does not support null keys. public void testColumnNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); - try { - table.column(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.column(null)); } public void testColumnSetPartialOverlap() { diff --git a/android/guava-tests/test/com/google/common/collect/AbstractTableTest.java b/android/guava-tests/test/com/google/common/collect/AbstractTableTest.java index 0639f2d325d0..264bb06f0a80 100644 --- a/android/guava-tests/test/com/google/common/collect/AbstractTableTest.java +++ b/android/guava-tests/test/com/google/common/collect/AbstractTableTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import java.util.Map; @@ -57,11 +58,7 @@ public void testClear() { assertEquals(0, table.size()); assertFalse(table.containsRow("foo")); } else { - try { - table.clear(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> table.clear()); } } @@ -81,25 +78,13 @@ public void testPut() { public void testPutNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSize(3); - try { - table.put(null, 2, cellValue('d')); - fail(); - } catch (NullPointerException expected) { - } - try { - table.put("cat", null, cellValue('d')); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.put(null, 2, cellValue('d'))); + assertThrows(NullPointerException.class, () -> table.put("cat", null, cellValue('d'))); if (supportsNullValues()) { assertNull(table.put("cat", 2, null)); assertTrue(table.contains("cat", 2)); } else { - try { - table.put("cat", 2, null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.put("cat", 2, null)); } assertSize(3); } @@ -111,11 +96,7 @@ public void testPutNullReplace() { assertEquals((Character) 'b', table.put("bar", 1, nullableCellValue(null))); assertNull(table.get("bar", 1)); } else { - try { - table.put("bar", 1, nullableCellValue(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.put("bar", 1, nullableCellValue(null))); } } @@ -150,11 +131,7 @@ public void testRemove() { assertNull(table.remove(null, null)); assertSize(2); } else { - try { - table.remove("foo", 3); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> table.remove("foo", 3)); assertEquals((Character) 'c', table.get("foo", 3)); } } diff --git a/android/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java b/android/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java index 20920362557b..bc18b493baa4 100644 --- a/android/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java +++ b/android/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -119,11 +120,7 @@ public void testSublistConcurrentModificationException() { assertTrue(sublist.isEmpty()); multimap.put("foo", 6); - try { - sublist.isEmpty(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - } + assertThrows(ConcurrentModificationException.class, () -> sublist.isEmpty()); } public void testCreateFromMultimap() { @@ -146,17 +143,9 @@ public void testCreateFromSizes() { } public void testCreateFromIllegalSizes() { - try { - ArrayListMultimap.create(15, -2); - fail(); - } catch (IllegalArgumentException expected) { - } - - try { - ArrayListMultimap.create(-15, 2); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ArrayListMultimap.create(15, -2)); + + assertThrows(IllegalArgumentException.class, () -> ArrayListMultimap.create(-15, 2)); } public void testCreateFromHashMultimap() { diff --git a/android/guava-tests/test/com/google/common/collect/ArrayTableTest.java b/android/guava-tests/test/com/google/common/collect/ArrayTableTest.java index f97a4393da7f..ca57d8f8a577 100644 --- a/android/guava-tests/test/com/google/common/collect/ArrayTableTest.java +++ b/android/guava-tests/test/com/google/common/collect/ArrayTableTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -187,35 +188,27 @@ public void testToStringSize1() { } public void testCreateDuplicateRows() { - try { - ArrayTable.create(asList("foo", "bar", "foo"), asList(1, 2, 3)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ArrayTable.create(asList("foo", "bar", "foo"), asList(1, 2, 3))); } public void testCreateDuplicateColumns() { - try { - ArrayTable.create(asList("foo", "bar"), asList(1, 2, 3, 2)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ArrayTable.create(asList("foo", "bar"), asList(1, 2, 3, 2))); } public void testCreateEmptyRows() { - try { - ArrayTable.create(Arrays.asList(), asList(1, 2, 3)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ArrayTable.create(Arrays.asList(), asList(1, 2, 3))); } public void testCreateEmptyColumns() { - try { - ArrayTable.create(asList("foo", "bar"), Arrays.asList()); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ArrayTable.create(asList("foo", "bar"), Arrays.asList())); } public void testCreateEmptyRowsXColumns() { @@ -227,11 +220,7 @@ public void testCreateEmptyRowsXColumns() { assertThat(table.rowKeyList()).isEmpty(); assertThat(table.columnKeySet()).isEmpty(); assertThat(table.rowKeySet()).isEmpty(); - try { - table.at(0, 0); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> table.at(0, 0)); } @GwtIncompatible // toArray @@ -361,26 +350,10 @@ public void testAt() { assertEquals((Character) 'b', table.at(1, 0)); assertEquals((Character) 'c', table.at(0, 2)); assertNull(table.at(1, 2)); - try { - table.at(1, 3); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.at(1, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.at(3, 2); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.at(-1, 2); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> table.at(1, 3)); + assertThrows(IndexOutOfBoundsException.class, () -> table.at(1, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> table.at(3, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> table.at(-1, 2)); } public void testSet() { @@ -392,26 +365,10 @@ public void testSet() { assertEquals((Character) 'e', table.get("cat", 1)); assertEquals((Character) 'a', table.set(0, 0, null)); assertNull(table.get("foo", 1)); - try { - table.set(1, 3, 'z'); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.set(1, -1, 'z'); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.set(3, 2, 'z'); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.set(-1, 2, 'z'); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> table.set(1, 3, 'z')); + assertThrows(IndexOutOfBoundsException.class, () -> table.set(1, -1, 'z')); + assertThrows(IndexOutOfBoundsException.class, () -> table.set(3, 2, 'z')); + assertThrows(IndexOutOfBoundsException.class, () -> table.set(-1, 2, 'z')); assertFalse(table.containsValue('z')); } @@ -427,18 +384,11 @@ public void testEraseAll() { public void testPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); - try { - table.put("dog", 1, 'd'); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Row dog not in [foo, bar, cat]"); - } - try { - table.put("foo", 4, 'd'); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Column 4 not in [1, 2, 3]"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> table.put("dog", 1, 'd')); + assertThat(expected).hasMessageThat().isEqualTo("Row dog not in [foo, bar, cat]"); + expected = assertThrows(IllegalArgumentException.class, () -> table.put("foo", 4, 'd')); + assertThat(expected).hasMessageThat().isEqualTo("Column 4 not in [1, 2, 3]"); assertFalse(table.containsValue('d')); } @@ -483,44 +433,30 @@ public void testRowMissing() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map row = table.row("dog"); assertTrue(row.isEmpty()); - try { - row.put(1, 'd'); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> row.put(1, 'd')); } public void testColumnMissing() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map column = table.column(4); assertTrue(column.isEmpty()); - try { - column.put("foo", 'd'); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> column.put("foo", 'd')); } public void testRowPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map map = table.row("foo"); - try { - map.put(4, 'd'); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Column 4 not in [1, 2, 3]"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> map.put(4, 'd')); + assertThat(expected).hasMessageThat().isEqualTo("Column 4 not in [1, 2, 3]"); } public void testColumnPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map map = table.column(3); - try { - map.put("dog", 'd'); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Row dog not in [foo, bar, cat]"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> map.put("dog", 'd')); + assertThat(expected).hasMessageThat().isEqualTo("Row dog not in [foo, bar, cat]"); } @J2ktIncompatible diff --git a/android/guava-tests/test/com/google/common/collect/ContiguousSetTest.java b/android/guava-tests/test/com/google/common/collect/ContiguousSetTest.java index 63edca44b7b5..abca6e75e499 100644 --- a/android/guava-tests/test/com/google/common/collect/ContiguousSetTest.java +++ b/android/guava-tests/test/com/google/common/collect/ContiguousSetTest.java @@ -19,6 +19,7 @@ import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.DiscreteDomain.integers; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.NON_STANDARD_TOSTRING; @@ -79,29 +80,13 @@ public Integer maxValue() { }; public void testInvalidIntRange() { - try { - ContiguousSet.closed(2, 1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - ContiguousSet.closedOpen(2, 1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ContiguousSet.closed(2, 1)); + assertThrows(IllegalArgumentException.class, () -> ContiguousSet.closedOpen(2, 1)); } public void testInvalidLongRange() { - try { - ContiguousSet.closed(2L, 1L); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - ContiguousSet.closedOpen(2L, 1L); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ContiguousSet.closed(2L, 1L)); + assertThrows(IllegalArgumentException.class, () -> ContiguousSet.closedOpen(2L, 1L)); } public void testEquals() { @@ -178,20 +163,16 @@ public long distance(Integer start, Integer end) { public void testCreate_noMin() { Range range = Range.lessThan(0); - try { - ContiguousSet.create(range, UNBOUNDED_THROWING_DOMAIN); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ContiguousSet.create(range, UNBOUNDED_THROWING_DOMAIN)); } public void testCreate_noMax() { Range range = Range.greaterThan(0); - try { - ContiguousSet.create(range, UNBOUNDED_THROWING_DOMAIN); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ContiguousSet.create(range, UNBOUNDED_THROWING_DOMAIN)); } public void testCreate_empty() { @@ -257,11 +238,7 @@ public void testSubSet() { public void testSubSet_outOfOrder() { ImmutableSortedSet set = ContiguousSet.create(Range.closed(1, 3), integers()); - try { - set.subSet(3, 2); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> set.subSet(3, 2)); } public void testSubSet_tooLarge() { diff --git a/android/guava-tests/test/com/google/common/collect/EnumBiMapTest.java b/android/guava-tests/test/com/google/common/collect/EnumBiMapTest.java index 93c45a340b73..88e80b3f96f2 100644 --- a/android/guava-tests/test/com/google/common/collect/EnumBiMapTest.java +++ b/android/guava-tests/test/com/google/common/collect/EnumBiMapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.orderEntriesByKey; import static com.google.common.truth.Truth.assertThat; @@ -152,16 +153,12 @@ public void testCreateFromMap() { assertEquals(Currency.DOLLAR, bimap.inverse().get(Country.CANADA)); /* Map must have at least one entry if not an EnumBiMap. */ - try { - EnumBiMap.create(Collections.emptyMap()); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } - try { - EnumBiMap.create(EnumHashBiMap.create(Currency.class)); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> EnumBiMap.create(Collections.emptyMap())); + assertThrows( + IllegalArgumentException.class, + () -> EnumBiMap.create(EnumHashBiMap.create(Currency.class))); /* Map can be empty if it's an EnumBiMap. */ Map emptyBimap = EnumBiMap.create(Currency.class, Country.class); diff --git a/android/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java b/android/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java index 02ae0b616284..352b069d322a 100644 --- a/android/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java +++ b/android/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -145,11 +147,9 @@ public void testCreateFromMap() { assertEquals(Currency.DOLLAR, bimap.inverse().get("dollar")); /* Map must have at least one entry if not an EnumHashBiMap. */ - try { - EnumHashBiMap.create(Collections.emptyMap()); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> EnumHashBiMap.create(Collections.emptyMap())); /* Map can be empty if it's an EnumHashBiMap. */ Map emptyBimap = EnumHashBiMap.create(Currency.class); diff --git a/android/guava-tests/test/com/google/common/collect/EnumMultisetTest.java b/android/guava-tests/test/com/google/common/collect/EnumMultisetTest.java index f40547793be8..4a3fc9d07e4e 100644 --- a/android/guava-tests/test/com/google/common/collect/EnumMultisetTest.java +++ b/android/guava-tests/test/com/google/common/collect/EnumMultisetTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; @@ -30,6 +31,7 @@ import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; import com.google.common.testing.SerializableTester; +import com.google.errorprone.annotations.Keep; import java.util.Collection; import java.util.EnumSet; import java.util.Set; @@ -108,11 +110,7 @@ public void testCollectionCreate() { public void testIllegalCreate() { Collection empty = EnumSet.noneOf(Color.class); - try { - EnumMultiset.create(empty); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> EnumMultiset.create(empty)); } public void testCreateEmptyWithClass() { @@ -121,11 +119,8 @@ public void testCreateEmptyWithClass() { } public void testCreateEmptyWithoutClassFails() { - try { - EnumMultiset.create(ImmutableList.of()); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> EnumMultiset.create(ImmutableList.of())); } public void testToString() { @@ -157,6 +152,7 @@ public void testEntrySet() { // create(Enum1.class) is equal to create(Enum2.class) but testEquals() expects otherwise. // For the same reason, we need to skip create(Iterable, Class). private static class EnumMultisetFactory { + @Keep // used reflectively by testEquals public static > EnumMultiset create(Iterable elements) { return EnumMultiset.create(elements); } diff --git a/android/guava-tests/test/com/google/common/collect/EvictingQueueTest.java b/android/guava-tests/test/com/google/common/collect/EvictingQueueTest.java index 0e23035d86a6..7ba7923aed5c 100644 --- a/android/guava-tests/test/com/google/common/collect/EvictingQueueTest.java +++ b/android/guava-tests/test/com/google/common/collect/EvictingQueueTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -36,11 +38,7 @@ public class EvictingQueueTest extends TestCase { public void testCreateWithNegativeSize() throws Exception { - try { - EvictingQueue.create(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> EvictingQueue.create(-1)); } public void testCreateWithZeroSize() throws Exception { @@ -56,19 +54,11 @@ public void testCreateWithZeroSize() throws Exception { assertFalse(queue.remove("hi")); assertEquals(0, queue.size()); - try { - queue.element(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> queue.element()); assertNull(queue.peek()); assertNull(queue.poll()); - try { - queue.remove(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> queue.remove()); } public void testRemainingCapacity_maxSize0() { diff --git a/android/guava-tests/test/com/google/common/collect/FluentIterableTest.java b/android/guava-tests/test/com/google/common/collect/FluentIterableTest.java index e77aad8848a8..76eede4212ed 100644 --- a/android/guava-tests/test/com/google/common/collect/FluentIterableTest.java +++ b/android/guava-tests/test/com/google/common/collect/FluentIterableTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -63,11 +64,9 @@ public void testFromArrayAndAppend() { public void testFromArrayAndIteratorRemove() { FluentIterable units = FluentIterable.from(TimeUnit.values()); - try { - Iterables.removeIf(units, Predicates.equalTo(TimeUnit.SECONDS)); - fail("Expected an UnsupportedOperationException to be thrown but it wasn't."); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, + () -> Iterables.removeIf(units, Predicates.equalTo(TimeUnit.SECONDS))); } public void testFrom() { @@ -131,11 +130,7 @@ public void testConcatNullPointerException() { List list1 = newArrayList(1); List list2 = newArrayList(4); - try { - FluentIterable.concat(list1, null, list2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> FluentIterable.concat(list1, null, list2)); } public void testConcatPeformingFiniteCycle() { @@ -326,12 +321,12 @@ public void testAppend_emptyList() { } public void testAppend_nullPointerException() { - try { - FluentIterable unused = - FluentIterable.from(asList(1, 2)).append((List) null); - fail("Appending null iterable should throw NPE."); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> { + FluentIterable unused = + FluentIterable.from(asList(1, 2)).append((List) null); + }); } /* @@ -423,11 +418,7 @@ public void testTransformWith_poorlyBehavedTransform() { Iterator resultIterator = iterable.iterator(); resultIterator.next(); - try { - resultIterator.next(); - fail("Transforming null to int should throw NumberFormatException"); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> resultIterator.next()); } private static final class StringValueOfFunction implements Function { @@ -482,11 +473,7 @@ public void testFirst_list() { public void testFirst_null() { List list = Lists.newArrayList(null, "a", "b"); - try { - FluentIterable.from(list).first(); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> FluentIterable.from(list).first()); } public void testFirst_emptyList() { @@ -521,11 +508,7 @@ public void testLast_list() { public void testLast_null() { List list = Lists.newArrayList("a", "b", null); - try { - FluentIterable.from(list).last(); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> FluentIterable.from(list).last()); } public void testLast_emptyList() { @@ -661,11 +644,8 @@ public void testSkip_structurallyModifiedSkipAllList() throws Exception { } public void testSkip_illegalArgument() { - try { - FluentIterable.from(asList("a", "b", "c")).skip(-1); - fail("Skipping negative number of elements should throw IllegalArgumentException."); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> FluentIterable.from(asList("a", "b", "c")).skip(-1)); } public void testLimit() { @@ -678,12 +658,12 @@ public void testLimit() { } public void testLimit_illegalArgument() { - try { - FluentIterable unused = - FluentIterable.from(Lists.newArrayList("a", "b", "c")).limit(-1); - fail("Passing negative number to limit(...) method should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> { + FluentIterable unused = + FluentIterable.from(Lists.newArrayList("a", "b", "c")).limit(-1); + }); } public void testIsEmpty() { @@ -751,19 +731,12 @@ public void testToMap() { } public void testToMap_nullKey() { - try { - fluent(1, null, 2).toMap(Functions.constant("foo")); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> fluent(1, null, 2).toMap(Functions.constant("foo"))); } public void testToMap_nullValue() { - try { - fluent(1, 2, 3).toMap(Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> fluent(1, 2, 3).toMap(Functions.constant(null))); } public void testIndex() { @@ -786,21 +759,21 @@ public Integer apply(String input) { } public void testIndex_nullKey() { - try { - ImmutableListMultimap unused = - fluent(1, 2, 3).index(Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> { + ImmutableListMultimap unused = + fluent(1, 2, 3).index(Functions.constant(null)); + }); } public void testIndex_nullValue() { - try { - ImmutableListMultimap unused = - fluent(1, null, 2).index(Functions.constant("foo")); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> { + ImmutableListMultimap unused = + fluent(1, null, 2).index(Functions.constant("foo")); + }); } public void testUniqueIndex() { @@ -818,43 +791,40 @@ public Integer apply(String input) { } public void testUniqueIndex_duplicateKey() { - try { - ImmutableMap unused = - FluentIterable.from(asList("one", "two", "three", "four")) - .uniqueIndex( - new Function() { - @Override - public Integer apply(String input) { - return input.length(); - } - }); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> { + ImmutableMap unused = + FluentIterable.from(asList("one", "two", "three", "four")) + .uniqueIndex( + new Function() { + @Override + public Integer apply(String input) { + return input.length(); + } + }); + }); } public void testUniqueIndex_nullKey() { - try { - fluent(1, 2, 3).uniqueIndex(Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> fluent(1, 2, 3).uniqueIndex(Functions.constant(null))); } public void testUniqueIndex_nullValue() { - try { - ImmutableMap unused = - fluent(1, null, 2) - .uniqueIndex( - new Function() { - @Override - public Object apply(@Nullable Integer input) { - return String.valueOf(input); - } - }); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> { + ImmutableMap unused = + fluent(1, null, 2) + .uniqueIndex( + new Function() { + @Override + public Object apply(@Nullable Integer input) { + return String.valueOf(input); + } + }); + }); } public void testCopyInto_list() { @@ -903,17 +873,13 @@ public void testGet() { } public void testGet_outOfBounds() { - try { - FluentIterable.from(Lists.newArrayList("a", "b", "c")).get(-1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows( + IndexOutOfBoundsException.class, + () -> FluentIterable.from(Lists.newArrayList("a", "b", "c")).get(-1)); - try { - FluentIterable.from(Lists.newArrayList("a", "b", "c")).get(3); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows( + IndexOutOfBoundsException.class, + () -> FluentIterable.from(Lists.newArrayList("a", "b", "c")).get(3)); } private static void assertCanIterateAgain(Iterable iterable) { diff --git a/android/guava-tests/test/com/google/common/collect/GeneralRangeTest.java b/android/guava-tests/test/com/google/common/collect/GeneralRangeTest.java index c50f1f5c46d1..cca29faecf08 100644 --- a/android/guava-tests/test/com/google/common/collect/GeneralRangeTest.java +++ b/android/guava-tests/test/com/google/common/collect/GeneralRangeTest.java @@ -16,6 +16,7 @@ import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -43,22 +44,18 @@ public class GeneralRangeTest extends TestCase { public void testCreateEmptyRangeFails() { for (BoundType lboundType : BoundType.values()) { for (BoundType uboundType : BoundType.values()) { - try { - GeneralRange.range(ORDERING, 4, lboundType, 2, uboundType); - fail("Expected IAE"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> GeneralRange.range(ORDERING, 4, lboundType, 2, uboundType)); } } } public void testCreateEmptyRangeOpenOpenFails() { for (Integer i : IN_ORDER_VALUES) { - try { - GeneralRange.<@Nullable Integer>range(ORDERING, i, OPEN, i, OPEN); - fail("Expected IAE"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> GeneralRange.<@Nullable Integer>range(ORDERING, i, OPEN, i, OPEN)); } } diff --git a/android/guava-tests/test/com/google/common/collect/HashBasedTableTest.java b/android/guava-tests/test/com/google/common/collect/HashBasedTableTest.java index 15ca3482d2e6..d5ed5751ad52 100644 --- a/android/guava-tests/test/com/google/common/collect/HashBasedTableTest.java +++ b/android/guava-tests/test/com/google/common/collect/HashBasedTableTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -73,17 +74,9 @@ public void testCreateWithValidSizes() { } public void testCreateWithInvalidSizes() { - try { - HashBasedTable.create(100, -5); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> HashBasedTable.create(100, -5)); - try { - HashBasedTable.create(-5, 20); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> HashBasedTable.create(-5, 20)); } public void testCreateCopy() { diff --git a/android/guava-tests/test/com/google/common/collect/HashMultimapTest.java b/android/guava-tests/test/com/google/common/collect/HashMultimapTest.java index 6943656b3938..0fa8ac353c9a 100644 --- a/android/guava-tests/test/com/google/common/collect/HashMultimapTest.java +++ b/android/guava-tests/test/com/google/common/collect/HashMultimapTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -102,17 +104,9 @@ public void testCreateFromSizes() { } public void testCreateFromIllegalSizes() { - try { - HashMultimap.create(-20, 15); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> HashMultimap.create(-20, 15)); - try { - HashMultimap.create(20, -15); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> HashMultimap.create(20, -15)); } public void testEmptyMultimapsEqual() { diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java index 36afc8f53a09..2164b89bb8ef 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -171,11 +172,8 @@ public void testBuilder_orderEntriesByValueAfterExactSizeBuild() { public void testBuilder_orderEntriesByValue_usedTwiceFails() { ImmutableBiMap.Builder builder = new Builder().orderEntriesByValue(Ordering.natural()); - try { - builder.orderEntriesByValue(Ordering.natural()); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows( + IllegalStateException.class, () -> builder.orderEntriesByValue(Ordering.natural())); } public void testBuilderPutAllWithEmptyMap() { @@ -212,38 +210,26 @@ public void testBuilderReuse() { public void testBuilderPutNullKey() { Builder builder = new Builder<>(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); } public void testBuilderPutNullValue() { Builder builder = new Builder<>(); - try { - builder.put("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("one", null)); } public void testBuilderPutNullKeyViaPutAll() { Builder builder = new Builder<>(); - try { - builder.putAll(Collections.singletonMap(null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap(null, 1))); } public void testBuilderPutNullValueViaPutAll() { Builder builder = new Builder<>(); - try { - builder.putAll(Collections.singletonMap("one", null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap("one", null))); } @SuppressWarnings("AlwaysThrows") @@ -253,12 +239,9 @@ public void testPuttingTheSameKeyTwiceThrowsOnBuild() { .put("one", 1) .put("one", 1); // throwing on this line would be even better - try { - builder.build(); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("one"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> builder.build()); + assertThat(expected.getMessage()).contains("one"); } public void testOf() { @@ -453,41 +436,22 @@ public void testOf() { } public void testOfNullKey() { - try { - ImmutableBiMap.of(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableBiMap.of(null, 1)); - try { - ImmutableBiMap.of("one", 1, null, 2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableBiMap.of("one", 1, null, 2)); } public void testOfNullValue() { - try { - ImmutableBiMap.of("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableBiMap.of("one", null)); - try { - ImmutableBiMap.of("one", 1, "two", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableBiMap.of("one", 1, "two", null)); } - @SuppressWarnings("AlwaysThrows") + @SuppressWarnings({"AlwaysThrows", "DistinctVarargsChecker"}) public void testOfWithDuplicateKey() { - try { - ImmutableBiMap.of("one", 1, "one", 1); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("one"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> ImmutableBiMap.of("one", 1, "one", 1)); + assertThat(expected.getMessage()).contains("one"); } public void testOfEntries() { @@ -496,18 +460,14 @@ public void testOfEntries() { public void testOfEntriesNull() { Entry<@Nullable Integer, Integer> nullKey = entry(null, 23); - try { - ImmutableBiMap.ofEntries((Entry) nullKey); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableBiMap.ofEntries((Entry) nullKey)); Entry nullValue = ImmutableBiMapTest.<@Nullable Integer>entry(23, null); - try { - ImmutableBiMap.ofEntries((Entry) nullValue); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableBiMap.ofEntries((Entry) nullValue)); } private static Entry entry(T key, T value) { @@ -578,13 +538,9 @@ public void testDuplicateValues() { .put("dos", 2) .buildOrThrow(); - try { - ImmutableBiMap.copyOf(map); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).containsMatch("1|2"); - // We don't specify which of the two dups should be reported. - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> ImmutableBiMap.copyOf(map)); + assertThat(expected.getMessage()).containsMatch("1|2"); } // TODO(b/172823566): Use mainline testToImmutableBiMap once CollectorTester is usable to java7. @@ -603,12 +559,7 @@ public void testToImmutableBiMap_exceptionOnDuplicateKey_java7_combine() { ImmutableBiMap.builder().put("one", 1).put("two", 2); ImmutableBiMap.Builder zat = ImmutableBiMap.builder().put("two", 22).put("three", 3); - try { - zis.combine(zat).build(); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> zis.combine(zat).build()); } // BiMap-specific tests @@ -616,11 +567,7 @@ public void testToImmutableBiMap_exceptionOnDuplicateKey_java7_combine() { @SuppressWarnings("DoNotCall") public void testForcePut() { BiMap bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2)); - try { - bimap.forcePut("three", 3); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> bimap.forcePut("three", 3)); } public void testKeySet() { diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java index 367384c78cb1..03770fde622d 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_ANY_NULL_QUERIES; @@ -87,11 +88,8 @@ public static Test suite() { } public void testBuilderWithExpectedKeysNegative() { - try { - ImmutableListMultimap.builderWithExpectedKeys(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> ImmutableListMultimap.builderWithExpectedKeys(-1)); } public void testBuilderWithExpectedKeysZero() { @@ -110,11 +108,7 @@ public void testBuilderWithExpectedKeysPositive() { public void testBuilderWithExpectedValuesPerKeyNegative() { ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); - try { - builder.expectedValuesPerKey(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.expectedValuesPerKey(-1)); } public void testBuilderWithExpectedValuesPerKeyZero() { @@ -139,16 +133,10 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } private static class StringHolder { @@ -265,52 +253,23 @@ public void testBuilderPutNullKey() { Multimap<@Nullable String, Integer> toPut = LinkedListMultimap.create(); toPut.put(null, 1); ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll(null, Arrays.asList(1, 2, 3)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll(null, 1, 2, 3); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll((Multimap) toPut); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); + assertThrows(NullPointerException.class, () -> builder.putAll(null, Arrays.asList(1, 2, 3))); + assertThrows(NullPointerException.class, () -> builder.putAll(null, 1, 2, 3)); + assertThrows( + NullPointerException.class, () -> builder.putAll((Multimap) toPut)); } public void testBuilderPutNullValue() { Multimap toPut = LinkedListMultimap.create(); toPut.put("foo", null); ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); - try { - builder.put("foo", null); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll("foo", Arrays.asList(1, null, 3)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll("foo", 1, null, 3); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll((Multimap) toPut); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("foo", null)); + assertThrows( + NullPointerException.class, () -> builder.putAll("foo", Arrays.asList(1, null, 3))); + assertThrows(NullPointerException.class, () -> builder.putAll("foo", 1, null, 3)); + assertThrows( + NullPointerException.class, () -> builder.putAll((Multimap) toPut)); } public void testBuilderOrderKeysBy() { @@ -420,21 +379,17 @@ public void testCopyOfImmutableListMultimap() { public void testCopyOfNullKey() { ArrayListMultimap<@Nullable String, Integer> input = ArrayListMultimap.create(); input.put(null, 1); - try { - ImmutableListMultimap.copyOf((ArrayListMultimap) input); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableListMultimap.copyOf((ArrayListMultimap) input)); } public void testCopyOfNullValue() { ArrayListMultimap input = ArrayListMultimap.create(); input.putAll("foo", Arrays.<@Nullable Integer>asList(1, null, 3)); - try { - ImmutableListMultimap.copyOf((ArrayListMultimap) input); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableListMultimap.copyOf((ArrayListMultimap) input)); } // TODO(b/172823566): Use mainline testToImmutableListMultimap once CollectorTester is usable. diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableListTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableListTest.java index 0ad68bcaf458..e64b5f6b540d 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableListTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableListTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import static com.google.common.truth.Truth.assertThat; @@ -195,19 +196,11 @@ public void testCreation_fourteenElements() { } public void testCreation_singletonNull() { - try { - ImmutableList.of((String) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.of((String) null)); } public void testCreation_withNull() { - try { - ImmutableList.of("a", null, "b"); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.of("a", null, "b")); } public void testCreation_generic() { @@ -235,20 +228,12 @@ public void testCopyOf_arrayOfOneElement() { } public void testCopyOf_nullArray() { - try { - ImmutableList.copyOf((String[]) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.copyOf((String[]) null)); } public void testCopyOf_arrayContainingOnlyNull() { @Nullable String[] array = new @Nullable String[] {null}; - try { - ImmutableList.copyOf((String[]) array); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.copyOf((String[]) array)); } public void testCopyOf_collection_empty() { @@ -276,11 +261,7 @@ public void testCopyOf_collection_general() { public void testCopyOf_collectionContainingNull() { Collection<@Nullable String> c = MinimalCollection.of("a", null, "b"); - try { - ImmutableList.copyOf((Collection) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.copyOf((Collection) c)); } public void testCopyOf_iterator_empty() { @@ -304,19 +285,12 @@ public void testCopyOf_iterator_general() { public void testCopyOf_iteratorContainingNull() { Iterator<@Nullable String> iterator = Arrays.<@Nullable String>asList("a", null, "b").iterator(); - try { - ImmutableList.copyOf((Iterator) iterator); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> ImmutableList.copyOf((Iterator) iterator)); } public void testCopyOf_iteratorNull() { - try { - ImmutableList.copyOf((Iterator) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.copyOf((Iterator) null)); } public void testCopyOf_concurrentlyMutating() { @@ -372,11 +346,7 @@ public void testCopyOf_shortcut_immutableList() { public void testBuilderAddArrayHandlesNulls() { @Nullable String[] elements = new @Nullable String[] {"a", null, "b"}; ImmutableList.Builder builder = ImmutableList.builder(); - try { - builder.add((String[]) elements); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add((String[]) elements)); ImmutableList result = builder.build(); /* @@ -393,11 +363,7 @@ public void testBuilderAddArrayHandlesNulls() { public void testBuilderAddCollectionHandlesNulls() { List<@Nullable String> elements = Arrays.asList("a", null, "b"); ImmutableList.Builder builder = ImmutableList.builder(); - try { - builder.addAll((List) elements); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.addAll((List) elements)); ImmutableList result = builder.build(); assertEquals(ImmutableList.of("a"), result); assertEquals(1, result.size()); @@ -423,11 +389,8 @@ public void testSortedCopyOf_natural_singleton() { public void testSortedCopyOf_natural_containsNull() { Collection<@Nullable Integer> c = MinimalCollection.of(1, 3, null, 2); - try { - ImmutableList.sortedCopyOf((Collection) c); - fail("Expected NPE"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> ImmutableList.sortedCopyOf((Collection) c)); } public void testSortedCopyOf() { @@ -450,11 +413,9 @@ public void testSortedCopyOf_singleton() { public void testSortedCopyOf_containsNull() { Collection<@Nullable String> c = MinimalCollection.of("a", "b", "A", null, "c"); - try { - ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, (Collection) c); - fail("Expected NPE"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, (Collection) c)); } // TODO(b/172823566): Use mainline testToImmutableList once CollectorTester is usable to java7. @@ -593,61 +554,43 @@ public void testComplexBuilder() { public void testBuilderAddHandlesNullsCorrectly() { ImmutableList.Builder builder = ImmutableList.builder(); - try { - builder.add((String) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add((String) null)); - try { - builder.add((String[]) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add((String[]) null)); - try { - builder.add("a", null, "b"); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add("a", null, "b")); } public void testBuilderAddAllHandlesNullsCorrectly() { + { ImmutableList.Builder builder = ImmutableList.builder(); - try { - builder.addAll((Iterable) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((Iterable) null)); } - try { - builder.addAll((Iterator) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + { + ImmutableList.Builder builder = ImmutableList.builder(); + assertThrows(NullPointerException.class, () -> builder.addAll((Iterator) null)); } - builder = ImmutableList.builder(); + { + ImmutableList.Builder builder = ImmutableList.builder(); List<@Nullable String> listWithNulls = asList("a", null, "b"); - try { - builder.addAll((List) listWithNulls); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((List) listWithNulls)); } - builder = ImmutableList.builder(); + { + ImmutableList.Builder builder = ImmutableList.builder(); Iterator<@Nullable String> iteratorWithNulls = Arrays.<@Nullable String>asList("a", null, "b").iterator(); - try { - builder.addAll((Iterator) iteratorWithNulls); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows( + NullPointerException.class, () -> builder.addAll((Iterator) iteratorWithNulls)); } + { + ImmutableList.Builder builder = ImmutableList.builder(); Iterable<@Nullable String> iterableWithNulls = MinimalIterable.of("a", null, "b"); - try { - builder.addAll((Iterable) iterableWithNulls); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows( + NullPointerException.class, () -> builder.addAll((Iterable) iterableWithNulls)); } } @@ -676,11 +619,10 @@ public void testAddOverflowCollection() { for (int i = 0; i < 100; i++) { builder.add("a"); } - try { - builder.addAll(Collections.nCopies(Integer.MAX_VALUE - 50, "a")); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("cannot store more than MAX_VALUE elements"); - } + IllegalArgumentException expected = + assertThrows( + IllegalArgumentException.class, + () -> builder.addAll(Collections.nCopies(Integer.MAX_VALUE - 50, "a"))); + assertThat(expected).hasMessageThat().contains("cannot store more than MAX_VALUE elements"); } } diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java index 6cb188d4d42e..ddd769bb052f 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; @@ -234,11 +235,8 @@ public void testBuilder_orderEntriesByValueAfterExactSizeBuild() { public void testBuilder_orderEntriesByValue_usedTwiceFails() { ImmutableMap.Builder builder = new Builder().orderEntriesByValue(Ordering.natural()); - try { - builder.orderEntriesByValue(Ordering.natural()); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows( + IllegalStateException.class, () -> builder.orderEntriesByValue(Ordering.natural())); } @GwtIncompatible // we haven't implemented this @@ -255,11 +253,7 @@ public void testBuilder_orderEntriesByValue_keepingLast() { .put("two", 2); assertMapEquals( builder.buildKeepingLast(), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); - try { - builder.buildOrThrow(); - fail("Expected exception from duplicate keys"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.buildOrThrow()); } @GwtIncompatible // we haven't implemented this @@ -280,11 +274,7 @@ public void testBuilder_orderEntriesByValue_keepingLast_builderSizeFieldPreserve .put("one", 1) .put("one", 1); assertMapEquals(builder.buildKeepingLast(), "one", 1); - try { - builder.buildOrThrow(); - fail("Expected exception from duplicate keys"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.buildOrThrow()); } public void testBuilder_withImmutableEntry() { @@ -295,16 +285,10 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } private static class StringHolder { @@ -366,22 +350,15 @@ public void testBuilderReuse() { public void testBuilderPutNullKeyFailsAtomically() { Builder builder = new Builder<>(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); builder.put("foo", 2); assertMapEquals(builder.buildOrThrow(), "foo", 2); } public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); builder.put("foo", 2); assertMapEquals(builder.buildOrThrow(), "foo", 2); } @@ -409,49 +386,34 @@ public V getValue() { public void testBuilderPutMutableEntryWithNullKeyFailsAtomically() { Builder builder = new Builder<>(); - try { - builder.put(new SimpleEntry(null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(new SimpleEntry(null, 1))); builder.put("foo", 2); assertMapEquals(builder.buildOrThrow(), "foo", 2); } public void testBuilderPutNullKey() { Builder builder = new Builder<>(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); } public void testBuilderPutNullValue() { Builder builder = new Builder<>(); - try { - builder.put("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("one", null)); } public void testBuilderPutNullKeyViaPutAll() { Builder builder = new Builder<>(); - try { - builder.putAll(Collections.singletonMap(null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap(null, 1))); } public void testBuilderPutNullValueViaPutAll() { Builder builder = new Builder<>(); - try { - builder.putAll(Collections.singletonMap("one", null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap("one", null))); } public void testPuttingTheSameKeyTwiceThrowsOnBuild() { @@ -460,11 +422,7 @@ public void testPuttingTheSameKeyTwiceThrowsOnBuild() { .put("one", 1) .put("one", 1); // throwing on this line might be better but it's too late to change - try { - builder.buildOrThrow(); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.buildOrThrow()); } public void testBuildKeepingLast_allowsOverwrite() { @@ -588,19 +546,16 @@ public void testBuilder_keepingLast_thenOrThrow() { .put("two", 2); assertMapEquals( builder.buildKeepingLast(), "three", 3, "one", 1, "five", 5, "four", 4, "two", 2); - try { - builder.buildOrThrow(); - fail("Expected exception from duplicate keys"); - } catch (IllegalArgumentException expected) { - // We don't really care which values the exception message contains, but they should be - // different from each other. If buildKeepingLast() collapsed duplicates, that might end up - // not being true. - Pattern pattern = Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)"); - assertThat(expected).hasMessageThat().matches(pattern); + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> builder.buildOrThrow()); + // We don't really care which values the exception message contains, but they should be + // different from each other. If buildKeepingLast() collapsed duplicates, that might end up not + // being true. + Pattern pattern = Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)"); + assertThat(expected).hasMessageThat().matches(pattern); Matcher matcher = pattern.matcher(expected.getMessage()); assertThat(matcher.matches()).isTrue(); assertThat(matcher.group(1)).isNotEqualTo(matcher.group(2)); - } } public void testOf() { @@ -763,39 +718,19 @@ public void testOf() { } public void testOfNullKey() { - try { - ImmutableMap.of(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMap.of(null, 1)); - try { - ImmutableMap.of("one", 1, null, 2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMap.of("one", 1, null, 2)); } public void testOfNullValue() { - try { - ImmutableMap.of("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMap.of("one", null)); - try { - ImmutableMap.of("one", 1, "two", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMap.of("one", 1, "two", null)); } public void testOfWithDuplicateKey() { - try { - ImmutableMap.of("one", 1, "one", 1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ImmutableMap.of("one", 1, "one", 1)); } public void testCopyOfEmptyMap() { @@ -837,12 +772,7 @@ public void testToImmutableMap_exceptionOnDuplicateKey_java7_combine() { ImmutableMap.builder().put("one", 1).put("two", 2); ImmutableMap.Builder zat = ImmutableMap.builder().put("two", 22).put("three", 3); - try { - zis.combine(zat).build(); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> zis.combine(zat).build()); } public static void hashtableTestHelper(ImmutableList sizes) { @@ -1079,17 +1009,13 @@ public void testEquals() { public void testOfEntriesNull() { Entry<@Nullable Integer, @Nullable Integer> nullKey = entry(null, 23); - try { - ImmutableMap.ofEntries((Entry) nullKey); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableMap.ofEntries((Entry) nullKey)); Entry<@Nullable Integer, @Nullable Integer> nullValue = entry(23, null); - try { - ImmutableMap.ofEntries((Entry) nullValue); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableMap.ofEntries((Entry) nullValue)); } private static Map map(T... keysAndValues) { diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableMultimapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableMultimapTest.java index 12dcf31b8ded..9dddb7b35e49 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableMultimapTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableMultimapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -50,24 +51,15 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } public void testBuilderWithExpectedKeysNegative() { - try { - ImmutableMultimap.builderWithExpectedKeys(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> ImmutableMultimap.builderWithExpectedKeys(-1)); } public void testBuilderWithExpectedKeysZero() { @@ -85,11 +77,8 @@ public void testBuilderWithExpectedKeysPositive() { } public void testBuilderWithExpectedValuesPerKeyNegative() { - try { - ImmutableMultimap.builder().expectedValuesPerKey(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> ImmutableMultimap.builder().expectedValuesPerKey(-1)); } public void testBuilderWithExpectedValuesPerKeyZero() { diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java index 3eb41097eaa7..2d71d274b72d 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -201,6 +202,7 @@ public void testCreation_arrayOfOneElement() { assertEquals(HashMultiset.create(asList("a")), multiset); } + @SuppressWarnings("ArrayAsKeyOfSetOrMap") public void testCreation_arrayOfArray() { String[] array = new String[] {"a"}; Multiset multiset = ImmutableMultiset.of(array); @@ -211,11 +213,7 @@ public void testCreation_arrayOfArray() { public void testCreation_arrayContainingOnlyNull() { @Nullable String[] array = new @Nullable String[] {null}; - try { - ImmutableMultiset.copyOf((String[]) array); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMultiset.copyOf((String[]) array)); } public void testCopyOf_collection_empty() { @@ -239,11 +237,8 @@ public void testCopyOf_collection_general() { public void testCopyOf_collectionContainingNull() { Collection<@Nullable String> c = MinimalCollection.of("a", null, "b"); - try { - ImmutableMultiset.copyOf((Collection) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> ImmutableMultiset.copyOf((Collection) c)); } public void testCopyOf_multiset_empty() { @@ -267,11 +262,7 @@ public void testCopyOf_multiset_general() { public void testCopyOf_multisetContainingNull() { Multiset<@Nullable String> c = HashMultiset.create(Arrays.<@Nullable String>asList("a", null, "b")); - try { - ImmutableMultiset.copyOf((Multiset) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMultiset.copyOf((Multiset) c)); } public void testCopyOf_iterator_empty() { @@ -295,11 +286,8 @@ public void testCopyOf_iterator_general() { public void testCopyOf_iteratorContainingNull() { Iterator<@Nullable String> iterator = Arrays.<@Nullable String>asList("a", null, "b").iterator(); - try { - ImmutableMultiset.copyOf((Iterator) iterator); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> ImmutableMultiset.copyOf((Iterator) iterator)); } private static class CountingIterable implements Iterable { @@ -409,73 +397,48 @@ public void testBuilderSetCount() { public void testBuilderAddHandlesNullsCorrectly() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.add((String) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add((String) null)); } public void testBuilderAddAllHandlesNullsCorrectly() { + { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.addAll((Collection) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((Collection) null)); } - builder = ImmutableMultiset.builder(); + { + ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); List<@Nullable String> listWithNulls = asList("a", null, "b"); - try { - builder.addAll((List) listWithNulls); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((List) listWithNulls)); } - builder = ImmutableMultiset.builder(); + { + ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); Multiset<@Nullable String> multisetWithNull = LinkedHashMultiset.create(Arrays.<@Nullable String>asList("a", null, "b")); - try { - builder.addAll((Multiset) multisetWithNull); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows( + NullPointerException.class, () -> builder.addAll((Multiset) multisetWithNull)); } } public void testBuilderAddCopiesHandlesNullsCorrectly() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.addCopies(null, 2); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.addCopies(null, 2)); } public void testBuilderAddCopiesIllegal() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.addCopies("a", -2); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.addCopies("a", -2)); } public void testBuilderSetCountHandlesNullsCorrectly() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.setCount(null, 2); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.setCount(null, 2)); } public void testBuilderSetCountIllegal() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.setCount("a", -2); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.setCount("a", -2)); } @J2ktIncompatible diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java index e9eb7fa80f42..8c7af1d8564d 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_ANY_NULL_QUERIES; @@ -87,11 +88,8 @@ public static Test suite() { } public void testBuilderWithExpectedKeysNegative() { - try { - ImmutableSetMultimap.builderWithExpectedKeys(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> ImmutableSetMultimap.builderWithExpectedKeys(-1)); } public void testBuilderWithExpectedKeysZero() { @@ -110,11 +108,7 @@ public void testBuilderWithExpectedKeysPositive() { public void testBuilderWithExpectedValuesPerKeyNegative() { ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder(); - try { - builder.expectedValuesPerKey(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.expectedValuesPerKey(-1)); } public void testBuilderWithExpectedValuesPerKeyZero() { @@ -134,11 +128,7 @@ public void testBuilderWithExpectedValuesPerKeyPositive() { public void testBuilderWithExpectedValuesPerKeyNegativeOrderValuesBy() { ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder().orderValuesBy(Ordering.natural()); - try { - builder.expectedValuesPerKey(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.expectedValuesPerKey(-1)); } public void testBuilderWithExpectedValuesPerKeyZeroOrderValuesBy() { @@ -197,16 +187,10 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } private static class StringHolder { @@ -311,52 +295,23 @@ public void testBuilderPutNullKey() { Multimap<@Nullable String, Integer> toPut = LinkedListMultimap.create(); toPut.put(null, 1); ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll(null, Arrays.asList(1, 2, 3)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll(null, 1, 2, 3); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll((Multimap) toPut); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); + assertThrows(NullPointerException.class, () -> builder.putAll(null, Arrays.asList(1, 2, 3))); + assertThrows(NullPointerException.class, () -> builder.putAll(null, 1, 2, 3)); + assertThrows( + NullPointerException.class, () -> builder.putAll((Multimap) toPut)); } public void testBuilderPutNullValue() { Multimap toPut = LinkedListMultimap.create(); toPut.put("foo", null); ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder(); - try { - builder.put("foo", null); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll("foo", Arrays.asList(1, null, 3)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll("foo", 4, null, 6); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll((Multimap) toPut); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("foo", null)); + assertThrows( + NullPointerException.class, () -> builder.putAll("foo", Arrays.asList(1, null, 3))); + assertThrows(NullPointerException.class, () -> builder.putAll("foo", 4, null, 6)); + assertThrows( + NullPointerException.class, () -> builder.putAll((Multimap) toPut)); } public void testBuilderOrderKeysBy() { @@ -491,21 +446,17 @@ public void testCopyOfImmutableSetMultimap() { public void testCopyOfNullKey() { HashMultimap<@Nullable String, Integer> input = HashMultimap.create(); input.put(null, 1); - try { - ImmutableSetMultimap.copyOf((Multimap) input); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableSetMultimap.copyOf((Multimap) input)); } public void testCopyOfNullValue() { HashMultimap input = HashMultimap.create(); input.putAll("foo", Arrays.<@Nullable Integer>asList(1, null, 3)); - try { - ImmutableSetMultimap.copyOf((Multimap) input); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableSetMultimap.copyOf((Multimap) input)); } // TODO(b/172823566): Use mainline testToImmutableSetMultimap once CollectorTester is usable. diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java index dcfc9ed479f6..d20a0c1f24d4 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -151,11 +152,8 @@ public void testBuilder() { @SuppressWarnings("DoNotCall") public void testBuilder_orderEntriesByValueFails() { ImmutableSortedMap.Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.orderEntriesByValue(Ordering.natural()); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, () -> builder.orderEntriesByValue(Ordering.natural())); } public void testBuilder_withImmutableEntry() { @@ -168,16 +166,10 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } private static class StringHolder { @@ -239,38 +231,26 @@ public void testBuilderReuse() { public void testBuilderPutNullKey() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); } public void testBuilderPutNullValue() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.put("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("one", null)); } public void testBuilderPutNullKeyViaPutAll() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.putAll(Collections.singletonMap(null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap(null, 1))); } public void testBuilderPutNullValueViaPutAll() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.putAll(Collections.singletonMap("one", null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap("one", null))); } public void testPuttingTheSameKeyTwiceThrowsOnBuild() { @@ -279,11 +259,7 @@ public void testPuttingTheSameKeyTwiceThrowsOnBuild() { .put("one", 1) .put("one", 2); // throwing on this line would be even better - try { - builder.build(); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.build()); } public void testOf() { @@ -447,39 +423,20 @@ public void testOf() { public void testOfNullKey() { Integer n = null; - try { - ImmutableSortedMap.of(n, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableSortedMap.of(n, 1)); - try { - ImmutableSortedMap.of("one", 1, null, 2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableSortedMap.of("one", 1, null, 2)); } public void testOfNullValue() { - try { - ImmutableSortedMap.of("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableSortedMap.of("one", null)); - try { - ImmutableSortedMap.of("one", 1, "two", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableSortedMap.of("one", 1, "two", null)); } + @SuppressWarnings("DistinctVarargsChecker") public void testOfWithDuplicateKey() { - try { - ImmutableSortedMap.of("one", 1, "one", 1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ImmutableSortedMap.of("one", 1, "one", 1)); } public void testCopyOfEmptyMap() { @@ -584,11 +541,7 @@ public void testCopyOfDuplicateKey() { new IntegerDiv10(35), "thirty five", new IntegerDiv10(12), "twelve"); - try { - ImmutableSortedMap.copyOf(original); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ImmutableSortedMap.copyOf(original)); } public void testImmutableMapCopyOfImmutableSortedMap() { @@ -646,13 +599,8 @@ public void testToImmutableSortedMap_exceptionOnDuplicateKey_java7_combine() { ImmutableSortedMap.naturalOrder().put("one", 1).put("two", 2); ImmutableSortedMap.Builder zat = ImmutableSortedMap.naturalOrder().put("two", 22).put("three", 3); - try { - ImmutableSortedMap.Builder combined = zis.combine(zat); - combined.build(); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - // expected - } + ImmutableSortedMap.Builder combined = zis.combine(zat); + assertThrows(IllegalArgumentException.class, () -> combined.build()); } // Other tests @@ -681,11 +629,9 @@ public void testNullValuesInCopyOfMap() { source.put(k, k); } source.put(j, null); - try { - ImmutableSortedMap.copyOf((Map) source); - fail("Expected NullPointerException in copyOf(" + source + ")"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableSortedMap.copyOf((Map) source)); } } } @@ -698,11 +644,9 @@ public void testNullValuesInCopyOfEntries() { source.put(k, k); } source.put(j, null); - try { - ImmutableSortedMap.copyOf((Set>) source.entrySet()); - fail("Expected NullPointerException in copyOf(" + source.entrySet() + ")"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableSortedMap.copyOf((Set>) source.entrySet())); } } } diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java index 220ed8b7e760..f40fb27a1e6b 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -259,20 +260,12 @@ public void testEmpty_subSet() { public void testEmpty_first() { SortedSet set = of(); - try { - set.first(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> set.first()); } public void testEmpty_last() { SortedSet set = of(); - try { - set.last(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> set.last()); } @J2ktIncompatible @@ -417,11 +410,7 @@ public void testOf_subSet() { assertSame(this.of(), set.subSet("a", "b")); assertSame(this.of(), set.subSet("g", "h")); assertSame(this.of(), set.subSet("c", "c")); - try { - set.subSet("e", "c"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> set.subSet("e", "c")); } @J2ktIncompatible @@ -540,11 +529,7 @@ public void testExplicit_subSet() { assertTrue(set.subSet("", "b").isEmpty()); assertTrue(set.subSet("vermont", "california").isEmpty()); assertTrue(set.subSet("aaa", "zzz").isEmpty()); - try { - set.subSet("quick", "the"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> set.subSet("quick", "the")); } public void testExplicit_first() { @@ -925,11 +910,7 @@ public void testLegacyComparable_builder_reverse() { @SuppressWarnings({"deprecation", "static-access", "DoNotCall"}) public void testBuilderMethod() { - try { - ImmutableSortedSet.builder(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> ImmutableSortedSet.builder()); } public void testAsList() { diff --git a/android/guava-tests/test/com/google/common/collect/ImmutableTableTest.java b/android/guava-tests/test/com/google/common/collect/ImmutableTableTest.java index f2ec3d4dd642..3c44409f6e31 100644 --- a/android/guava-tests/test/com/google/common/collect/ImmutableTableTest.java +++ b/android/guava-tests/test/com/google/common/collect/ImmutableTableTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -82,24 +83,14 @@ public void testBuilder_withImmutableCell() { public void testBuilder_withImmutableCellAndNullContents() { ImmutableTable.Builder builder = new ImmutableTable.Builder<>(); - try { - builder.put(Tables.immutableCell((Character) null, 1, "foo")); - fail(); - } catch (NullPointerException e) { - // success - } - try { - builder.put(Tables.immutableCell('a', (Integer) null, "foo")); - fail(); - } catch (NullPointerException e) { - // success - } - try { - builder.put(Tables.immutableCell('a', 1, (String) null)); - fail(); - } catch (NullPointerException e) { - // success - } + assertThrows( + NullPointerException.class, + () -> builder.put(Tables.immutableCell((Character) null, 1, "foo"))); + assertThrows( + NullPointerException.class, + () -> builder.put(Tables.immutableCell('a', (Integer) null, "foo"))); + assertThrows( + NullPointerException.class, () -> builder.put(Tables.immutableCell('a', 1, (String) null))); } private static class StringHolder { @@ -144,34 +135,14 @@ public void testBuilder_noDuplicates() { new ImmutableTable.Builder() .put('a', 1, "foo") .put('a', 1, "bar"); - try { - builder.build(); - fail(); - } catch (IllegalArgumentException e) { - // success - } + assertThrows(IllegalArgumentException.class, () -> builder.build()); } public void testBuilder_noNulls() { ImmutableTable.Builder builder = new ImmutableTable.Builder<>(); - try { - builder.put(null, 1, "foo"); - fail(); - } catch (NullPointerException e) { - // success - } - try { - builder.put('a', null, "foo"); - fail(); - } catch (NullPointerException e) { - // success - } - try { - builder.put('a', 1, null); - fail(); - } catch (NullPointerException e) { - // success - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1, "foo")); + assertThrows(NullPointerException.class, () -> builder.put('a', null, "foo")); + assertThrows(NullPointerException.class, () -> builder.put('a', 1, null)); } private static void validateTableCopies(Table original) { diff --git a/android/guava-tests/test/com/google/common/collect/IterablesTest.java b/android/guava-tests/test/com/google/common/collect/IterablesTest.java index 600eddc42d0d..471e48b9f815 100644 --- a/android/guava-tests/test/com/google/common/collect/IterablesTest.java +++ b/android/guava-tests/test/com/google/common/collect/IterablesTest.java @@ -18,6 +18,7 @@ import static com.google.common.collect.Iterables.skip; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; @@ -151,20 +152,12 @@ public void testGetOnlyElement_noDefault_valid() { public void testGetOnlyElement_noDefault_empty() { Iterable iterable = Collections.emptyList(); - try { - Iterables.getOnlyElement(iterable); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> Iterables.getOnlyElement(iterable)); } public void testGetOnlyElement_noDefault_multiple() { Iterable iterable = asList("foo", "bar"); - try { - Iterables.getOnlyElement(iterable); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterables.getOnlyElement(iterable)); } public void testGetOnlyElement_withDefault_singleton() { @@ -184,11 +177,7 @@ public void testGetOnlyElement_withDefault_empty_null() { public void testGetOnlyElement_withDefault_multiple() { Iterable iterable = asList("foo", "bar"); - try { - Iterables.getOnlyElement(iterable, "x"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterables.getOnlyElement(iterable, "x")); } @GwtIncompatible // Iterables.toArray(Iterable, Class) @@ -239,11 +228,8 @@ public void testFind() { Iterable list = newArrayList("cool", "pants"); assertEquals("cool", Iterables.find(list, Predicates.equalTo("cool"))); assertEquals("pants", Iterables.find(list, Predicates.equalTo("pants"))); - try { - Iterables.find(list, Predicates.alwaysFalse()); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows( + NoSuchElementException.class, () -> Iterables.find(list, Predicates.alwaysFalse())); assertEquals("cool", Iterables.find(list, Predicates.alwaysTrue())); assertCanIterateAgain(list); } @@ -315,11 +301,7 @@ public Integer apply(String from) { Iterator resultIterator = result.iterator(); resultIterator.next(); - try { - resultIterator.next(); - fail("Expected NFE"); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> resultIterator.next()); } public void testNullFriendlyTransform() { @@ -397,11 +379,7 @@ public void testConcatNullPointerException() { List list1 = newArrayList(1); List list2 = newArrayList(4); - try { - Iterables.concat(list1, null, list2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Iterables.concat(list1, null, list2)); } public void testConcatPeformingFiniteCycle() { @@ -413,11 +391,7 @@ public void testConcatPeformingFiniteCycle() { public void testPartition_badSize() { Iterable source = Collections.singleton(1); - try { - Iterables.partition(source, 0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterables.partition(source, 0)); } public void testPartition_empty() { @@ -570,11 +544,7 @@ public void testLimit() { public void testLimit_illegalArgument() { List list = newArrayList("a", "b", "c"); - try { - Iterables.limit(list, -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterables.limit(list, -1)); } public void testIsEmpty() { @@ -625,31 +595,19 @@ public void testSkip_removal() { } catch (NoSuchElementException suppressed) { // We want remove() to fail even after a failed call to next(). } - try { - iterator.remove(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> iterator.remove()); } public void testSkip_allOfMutableList_modifiable() { List list = newArrayList("a", "b"); Iterator iterator = skip(list, 2).iterator(); - try { - iterator.remove(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> iterator.remove()); } public void testSkip_allOfImmutableList_modifiable() { List list = ImmutableList.of("a", "b"); Iterator iterator = skip(list, 2).iterator(); - try { - iterator.remove(); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); } @GwtIncompatible // slow (~35s) @@ -717,11 +675,7 @@ public void testSkip_structurallyModifiedSkipAllList() throws Exception { public void testSkip_illegalArgument() { List list = newArrayList("a", "b", "c"); - try { - skip(list, -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> skip(list, -1)); } private void testGetOnAbc(Iterable iterable) { @@ -778,12 +732,8 @@ public void testGet_emptyIterable() { } public void testGet_withDefault_negativePosition() { - try { - Iterables.get(newArrayList("a", "b", "c"), -1, "d"); - fail(); - } catch (IndexOutOfBoundsException expected) { - // pass - } + assertThrows( + IndexOutOfBoundsException.class, () -> Iterables.get(newArrayList("a", "b", "c"), -1, "d")); } public void testGet_withDefault_simple() { @@ -839,11 +789,7 @@ public void testGetLast_list() { public void testGetLast_emptyList() { List list = Collections.emptyList(); - try { - Iterables.getLast(list); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows(NoSuchElementException.class, () -> Iterables.getLast(list)); } public void testGetLast_sortedSet() { @@ -893,11 +839,7 @@ public void testGetLast_withDefault_not_empty_list() { public void testGetLast_emptySortedSet() { SortedSet sortedSet = ImmutableSortedSet.of(); - try { - Iterables.getLast(sortedSet); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows(NoSuchElementException.class, () -> Iterables.getLast(sortedSet)); } public void testGetLast_iterable() { @@ -907,11 +849,7 @@ public void testGetLast_iterable() { public void testGetLast_emptyIterable() { Set set = Sets.newHashSet(); - try { - Iterables.getLast(set); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows(NoSuchElementException.class, () -> Iterables.getLast(set)); } public void testUnmodifiableIterable() { @@ -919,11 +857,7 @@ public void testUnmodifiableIterable() { Iterable iterable = Iterables.unmodifiableIterable(list); Iterator iterator = iterable.iterator(); iterator.next(); - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); assertEquals("[a, b, c]", iterable.toString()); } @@ -1193,12 +1127,7 @@ public void testConsumingIterable_duelingIterators() { Iterator i2 = Iterables.consumingIterable(list).iterator(); i1.next(); - try { - i2.next(); - fail("Concurrent modification should throw an exception."); - } catch (ConcurrentModificationException cme) { - // Pass - } + assertThrows(ConcurrentModificationException.class, () -> i2.next()); } public void testConsumingIterable_queue_iterator() { @@ -1313,12 +1242,7 @@ public void testMergeSorted_empty() { // Verify Iterator iterator = iterable.iterator(); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail("next() on empty iterator should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // Huzzah! - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); } public void testMergeSorted_single_empty() { diff --git a/android/guava-tests/test/com/google/common/collect/IteratorsTest.java b/android/guava-tests/test/com/google/common/collect/IteratorsTest.java index 063e7373d2ce..8ebfdb13fb12 100644 --- a/android/guava-tests/test/com/google/common/collect/IteratorsTest.java +++ b/android/guava-tests/test/com/google/common/collect/IteratorsTest.java @@ -21,6 +21,7 @@ import static com.google.common.collect.Iterators.get; import static com.google.common.collect.Iterators.getLast; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.truth.Truth.assertThat; @@ -83,16 +84,8 @@ public static Test suite() { public void testEmptyIterator() { Iterator iterator = Iterators.emptyIterator(); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail("no exception thrown"); - } catch (NoSuchElementException expected) { - } - try { - iterator.remove(); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); } @SuppressWarnings("DoNotCall") @@ -102,46 +95,18 @@ public void testEmptyListIterator() { assertFalse(iterator.hasPrevious()); assertEquals(0, iterator.nextIndex()); assertEquals(-1, iterator.previousIndex()); - try { - iterator.next(); - fail("no exception thrown"); - } catch (NoSuchElementException expected) { - } - try { - iterator.previous(); - fail("no exception thrown"); - } catch (NoSuchElementException expected) { - } - try { - iterator.remove(); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } - try { - iterator.set("a"); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } - try { - iterator.add("a"); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); + assertThrows(NoSuchElementException.class, () -> iterator.previous()); + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); + assertThrows(UnsupportedOperationException.class, () -> iterator.set("a")); + assertThrows(UnsupportedOperationException.class, () -> iterator.add("a")); } public void testEmptyModifiableIterator() { Iterator iterator = Iterators.emptyModifiableIterator(); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail("Expected NoSuchElementException"); - } catch (NoSuchElementException expected) { - } - try { - iterator.remove(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); + assertThrows(IllegalStateException.class, () -> iterator.remove()); } public void testSize0() { @@ -188,45 +153,32 @@ public void testGetOnlyElement_noDefault_valid() { public void testGetOnlyElement_noDefault_empty() { Iterator iterator = Iterators.emptyIterator(); - try { - Iterators.getOnlyElement(iterator); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> Iterators.getOnlyElement(iterator)); } public void testGetOnlyElement_noDefault_moreThanOneLessThanFiveElements() { Iterator iterator = asList("one", "two").iterator(); - try { - Iterators.getOnlyElement(iterator); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: "); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> Iterators.getOnlyElement(iterator)); + assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: "); } public void testGetOnlyElement_noDefault_fiveElements() { Iterator iterator = asList("one", "two", "three", "four", "five").iterator(); - try { - Iterators.getOnlyElement(iterator); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("expected one element but was: "); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> Iterators.getOnlyElement(iterator)); + assertThat(expected) + .hasMessageThat() + .isEqualTo("expected one element but was: "); } public void testGetOnlyElement_noDefault_moreThanFiveElements() { Iterator iterator = asList("one", "two", "three", "four", "five", "six").iterator(); - try { - Iterators.getOnlyElement(iterator); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("expected one element but was: "); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> Iterators.getOnlyElement(iterator)); + assertThat(expected) + .hasMessageThat() + .isEqualTo("expected one element but was: "); } public void testGetOnlyElement_withDefault_singleton() { @@ -246,12 +198,9 @@ public void testGetOnlyElement_withDefault_empty_null() { public void testGetOnlyElement_withDefault_two() { Iterator iterator = asList("foo", "bar").iterator(); - try { - Iterators.getOnlyElement(iterator, "x"); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: "); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> Iterators.getOnlyElement(iterator, "x")); + assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: "); } @GwtIncompatible // Iterators.toArray(Iterator, Class) @@ -375,11 +324,8 @@ public void testFind_lastElement() { public void testFind_notPresent() { Iterable list = Lists.newArrayList("cool", "pants"); Iterator iterator = list.iterator(); - try { - Iterators.find(iterator, Predicates.alwaysFalse()); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows( + NoSuchElementException.class, () -> Iterators.find(iterator, Predicates.alwaysFalse())); assertFalse(iterator.hasNext()); } @@ -505,11 +451,7 @@ public Integer apply(String from) { }); result.next(); - try { - result.next(); - fail("Expected NFE"); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> result.next()); } public void testNullFriendlyTransform() { @@ -586,33 +528,21 @@ public void testCycleOfTwoWithRemove() { public void testCycleRemoveWithoutNext() { Iterator cycle = Iterators.cycle("a", "b"); assertTrue(cycle.hasNext()); - try { - cycle.remove(); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> cycle.remove()); } public void testCycleRemoveSameElementTwice() { Iterator cycle = Iterators.cycle("a", "b"); cycle.next(); cycle.remove(); - try { - cycle.remove(); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> cycle.remove()); } public void testCycleWhenRemoveIsNotSupported() { Iterable iterable = asList("a", "b"); Iterator cycle = Iterators.cycle(iterable); cycle.next(); - try { - cycle.remove(); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> cycle.remove()); } public void testCycleRemoveAfterHasNext() { @@ -696,11 +626,7 @@ public void testCycleNoSuchElementException() { assertEquals("a", cycle.next()); cycle.remove(); assertFalse(cycle.hasNext()); - try { - cycle.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> cycle.next()); } @GwtIncompatible // unreasonably slow @@ -828,25 +754,17 @@ public void testConcatContainingNull() { Iterator result = Iterators.concat(input); assertEquals(1, (int) result.next()); assertEquals(2, (int) result.next()); - try { - result.hasNext(); - fail("no exception thrown"); - } catch (NullPointerException e) { - } - try { - result.next(); - fail("no exception thrown"); - } catch (NullPointerException e) { - } + assertThrows(NullPointerException.class, () -> result.hasNext()); + assertThrows(NullPointerException.class, () -> result.next()); // There is no way to get "through" to the 3. Buh-bye } public void testConcatVarArgsContainingNull() { - try { - Iterators.concat(iterateOver(1, 2), null, iterateOver(3), iterateOver(4), iterateOver(5)); - fail("no exception thrown"); - } catch (NullPointerException e) { - } + assertThrows( + NullPointerException.class, + () -> + Iterators.concat( + iterateOver(1, 2), null, iterateOver(3), iterateOver(4), iterateOver(5))); } public void testConcatNested_appendToEnd() { @@ -977,11 +895,7 @@ public void testElementsEqual() { public void testPartition_badSize() { Iterator source = Iterators.singletonIterator(1); - try { - Iterators.partition(source, 0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterators.partition(source, 0)); } public void testPartition_empty() { @@ -1048,11 +962,7 @@ public void testPartitionRandomAccess() { public void testPaddedPartition_badSize() { Iterator source = Iterators.singletonIterator(1); - try { - Iterators.paddedPartition(source, 0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterators.paddedPartition(source, 0)); } public void testPaddedPartition_empty() { @@ -1119,16 +1029,8 @@ public void testForArrayEmpty() { String[] array = new String[0]; Iterator iterator = Iterators.forArray(array); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException expected) { - } - try { - Iterators.forArrayWithPosition(array, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); + assertThrows(IndexOutOfBoundsException.class, () -> Iterators.forArrayWithPosition(array, 1)); } @SuppressWarnings("DoNotCall") @@ -1138,18 +1040,10 @@ public void testForArrayTypical() { assertTrue(iterator.hasNext()); assertEquals("foo", iterator.next()); assertTrue(iterator.hasNext()); - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); assertEquals("bar", iterator.next()); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); } public void testForArrayWithPosition() { @@ -1165,16 +1059,8 @@ public void testForArrayWithPosition() { public void testForArrayLengthWithPositionBoundaryCases() { String[] array = {"foo", "bar"}; assertFalse(Iterators.forArrayWithPosition(array, 2).hasNext()); - try { - Iterators.forArrayWithPosition(array, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - Iterators.forArrayWithPosition(array, 3); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> Iterators.forArrayWithPosition(array, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> Iterators.forArrayWithPosition(array, 3)); } @GwtIncompatible // unreasonably slow @@ -1198,11 +1084,7 @@ public void testForEnumerationEmpty() { Iterator iter = Iterators.forEnumeration(enumer); assertFalse(iter.hasNext()); - try { - iter.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> iter.next()); } @SuppressWarnings("DoNotCall") @@ -1213,17 +1095,9 @@ public void testForEnumerationSingleton() { assertTrue(iter.hasNext()); assertTrue(iter.hasNext()); assertEquals(1, (int) iter.next()); - try { - iter.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iter.remove()); assertFalse(iter.hasNext()); - try { - iter.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> iter.next()); } public void testForEnumerationTypical() { @@ -1244,11 +1118,7 @@ public void testAsEnumerationEmpty() { Enumeration enumer = Iterators.asEnumeration(iter); assertFalse(enumer.hasMoreElements()); - try { - enumer.nextElement(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> enumer.nextElement()); } public void testAsEnumerationSingleton() { @@ -1259,11 +1129,7 @@ public void testAsEnumerationSingleton() { assertTrue(enumer.hasMoreElements()); assertEquals(1, (int) enumer.nextElement()); assertFalse(enumer.hasMoreElements()); - try { - enumer.nextElement(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> enumer.nextElement()); } public void testAsEnumerationTypical() { @@ -1303,11 +1169,7 @@ public void testToStringEmptyIterator() { @SuppressWarnings("JUnitIncompatibleType") // Fails with j2kt. public void testLimit() { List list = newArrayList(); - try { - Iterators.limit(list.iterator(), -1); - fail("expected exception"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterators.limit(list.iterator(), -1)); assertFalse(Iterators.limit(list.iterator(), 0).hasNext()); assertFalse(Iterators.limit(list.iterator(), 1).hasNext()); @@ -1377,11 +1239,7 @@ public void testGetLast_basic() { public void testGetLast_exception() { List list = newArrayList(); - try { - getLast(list.iterator()); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> getLast(list.iterator())); } public void testGetLast_withDefault_singleton() { @@ -1418,11 +1276,7 @@ public void testGet_atSize() { list.add("a"); list.add("b"); Iterator iterator = list.iterator(); - try { - get(iterator, 2); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, 2)); assertFalse(iterator.hasNext()); } @@ -1431,33 +1285,21 @@ public void testGet_pastEnd() { list.add("a"); list.add("b"); Iterator iterator = list.iterator(); - try { - get(iterator, 5); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, 5)); assertFalse(iterator.hasNext()); } public void testGet_empty() { List list = newArrayList(); Iterator iterator = list.iterator(); - try { - get(iterator, 0); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, 0)); assertFalse(iterator.hasNext()); } public void testGet_negativeIndex() { List list = newArrayList("a", "b", "c"); Iterator iterator = list.iterator(); - try { - get(iterator, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, -1)); } public void testGet_withDefault_basic() { @@ -1492,12 +1334,7 @@ public void testGet_withDefault_negativeIndex() { list.add("a"); list.add("b"); Iterator iterator = list.iterator(); - try { - get(iterator, -1, "c"); - fail(); - } catch (IndexOutOfBoundsException expected) { - // pass - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, -1, "c")); assertTrue(iterator.hasNext()); } @@ -1522,11 +1359,7 @@ public void testAdvance_pastEnd() { public void testAdvance_illegalArgument() { List list = newArrayList("a", "b", "c"); Iterator iterator = list.iterator(); - try { - advance(iterator, -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> advance(iterator, -1)); } public void testFrequency() { @@ -1655,12 +1488,7 @@ public void testConsumingIterator_duelingIterators() { Iterator i2 = Iterators.consumingIterator(list.iterator()); i1.next(); - try { - i2.next(); - fail("Concurrent modification should throw an exception."); - } catch (ConcurrentModificationException cme) { - // Pass - } + assertThrows(ConcurrentModificationException.class, () -> i2.next()); } public void testIndexOf_consumedData() { diff --git a/android/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java b/android/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java index 5192bb8297e5..702d318caf11 100644 --- a/android/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java +++ b/android/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.Helpers.mapEntry; @@ -269,17 +270,9 @@ public void testCreateFromSizes() { } public void testCreateFromIllegalSizes() { - try { - LinkedHashMultimap.create(-20, 15); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> LinkedHashMultimap.create(-20, 15)); - try { - LinkedHashMultimap.create(20, -15); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> LinkedHashMultimap.create(20, -15)); } @GwtIncompatible // unreasonably slow diff --git a/android/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java b/android/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java index a8c6fd83a11e..a357c842e217 100644 --- a/android/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java +++ b/android/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; @@ -147,11 +148,7 @@ public void testCreateFromSize() { } public void testCreateFromIllegalSize() { - try { - LinkedListMultimap.create(-20); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> LinkedListMultimap.create(-20)); } public void testLinkedGetAdd() { @@ -296,18 +293,15 @@ public void testLinkedAsMapEntries() { map.put("foo", 2); map.put("bar", 3); Iterator>> entries = map.asMap().entrySet().iterator(); - Entry> entry = entries.next(); - assertEquals("bar", entry.getKey()); - assertThat(entry.getValue()).containsExactly(1, 3).inOrder(); - try { - entry.setValue(Arrays.asList()); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + Entry> barEntry = entries.next(); + assertEquals("bar", barEntry.getKey()); + assertThat(barEntry.getValue()).containsExactly(1, 3).inOrder(); + assertThrows( + UnsupportedOperationException.class, () -> barEntry.setValue(Arrays.asList())); entries.remove(); // clear - entry = entries.next(); - assertEquals("foo", entry.getKey()); - assertThat(entry.getValue()).contains(2); + Entry> fooEntry = entries.next(); + assertEquals("foo", fooEntry.getKey()); + assertThat(fooEntry.getValue()).contains(2); assertFalse(entries.hasNext()); assertEquals("{foo=[2]}", map.toString()); } diff --git a/android/guava-tests/test/com/google/common/collect/ListsTest.java b/android/guava-tests/test/com/google/common/collect/ListsTest.java index b3e92599af72..d89365b66f3c 100644 --- a/android/guava-tests/test/com/google/common/collect/ListsTest.java +++ b/android/guava-tests/test/com/google/common/collect/ListsTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -330,11 +331,7 @@ public void testNewArrayListWithCapacity() { } public void testNewArrayListWithCapacity_negative() { - try { - Lists.newArrayListWithCapacity(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Lists.newArrayListWithCapacity(-1)); } public void testNewArrayListWithExpectedSize() { @@ -346,11 +343,7 @@ public void testNewArrayListWithExpectedSize() { } public void testNewArrayListWithExpectedSize_negative() { - try { - Lists.newArrayListWithExpectedSize(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Lists.newArrayListWithExpectedSize(-1)); } public void testNewArrayListVarArgs() { @@ -433,18 +426,10 @@ public void testArraysAsList() { assertEquals("FOO", otherWay.get(0)); // But it can't grow - try { - otherWay.add("nope"); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> otherWay.add("nope")); // And it can't shrink - try { - otherWay.remove(2); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> otherWay.remove(2)); } @J2ktIncompatible @@ -658,11 +643,8 @@ public void testCartesianProduct_unrelatedTypes() { public void testCartesianProductTooBig() { List list = Collections.nCopies(10000, "foo"); - try { - Lists.cartesianProduct(list, list, list, list, list); - fail("Expected IAE"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> Lists.cartesianProduct(list, list, list, list, list)); } public void testTransformHashCodeRandomAccess() { @@ -771,20 +753,18 @@ public void testTransformListIteratorSequential() { } public void testTransformPreservesIOOBEsThrownByFunction() { - try { - Lists.transform( - ImmutableList.of("foo", "bar"), - new Function() { - @Override - public String apply(String input) { - throw new IndexOutOfBoundsException(); - } - }) - .toArray(); - fail(); - } catch (IndexOutOfBoundsException expected) { - // success - } + assertThrows( + IndexOutOfBoundsException.class, + () -> + Lists.transform( + ImmutableList.of("foo", "bar"), + new Function() { + @Override + public String apply(String input) { + throw new IndexOutOfBoundsException(); + } + }) + .toArray()); } private static void assertTransformListIterator(List list) { @@ -900,11 +880,7 @@ private static void assertTransformIterator(List list) { public void testPartition_badSize() { List source = Collections.singletonList(1); - try { - Lists.partition(source, 0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Lists.partition(source, 0)); } public void testPartition_empty() { diff --git a/android/guava-tests/test/com/google/common/collect/MapMakerTest.java b/android/guava-tests/test/com/google/common/collect/MapMakerTest.java index 563c9802f8aa..0bc48dde11b2 100644 --- a/android/guava-tests/test/com/google/common/collect/MapMakerTest.java +++ b/android/guava-tests/test/com/google/common/collect/MapMakerTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; import com.google.common.annotations.GwtCompatible; @@ -62,11 +63,7 @@ public T apply(T key) { public void testInitialCapacity_negative() { MapMaker maker = new MapMaker(); - try { - maker.initialCapacity(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> maker.initialCapacity(-1)); } // TODO(cpovirk): enable when ready (apparently after a change to our GWT emulation) diff --git a/android/guava-tests/test/com/google/common/collect/MapsTest.java b/android/guava-tests/test/com/google/common/collect/MapsTest.java index 8ce8be9eca20..5df96ffae604 100644 --- a/android/guava-tests/test/com/google/common/collect/MapsTest.java +++ b/android/guava-tests/test/com/google/common/collect/MapsTest.java @@ -19,6 +19,7 @@ import static com.google.common.collect.Maps.transformEntries; import static com.google.common.collect.Maps.transformValues; import static com.google.common.collect.Maps.unmodifiableNavigableMap; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; @@ -101,11 +102,7 @@ public void testHashMapGeneralizesTypes() { } public void testCapacityForNegativeSizeFails() { - try { - Maps.capacity(-1); - fail("Negative expected size must result in IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Maps.capacity(-1)); } /** @@ -335,11 +332,9 @@ public void testEnumMap() { } public void testEnumMapNullClass() { - try { - Maps.newEnumMap((Class) null); - fail("no exception thrown"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Maps.newEnumMap((Class) null)); } public void testEnumMapWithInitialEnumMap() { @@ -365,11 +360,7 @@ public void testEnumMapWithInitialMap() { public void testEnumMapWithInitialEmptyMap() { Map original = Maps.newHashMap(); - try { - Maps.newEnumMap(original); - fail("Empty map must result in an IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Maps.newEnumMap(original)); } public void testToStringImplWithNullKeys() throws Exception { @@ -627,21 +618,9 @@ public void testSortedMapDifferenceImmutable() { Maps.immutableEntry(3, ValueDifferenceImpl.create("c", "f")), Maps.immutableEntry(5, ValueDifferenceImpl.create("e", "g"))) .inOrder(); - try { - diff1.entriesInCommon().put(7, "x"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - diff1.entriesOnlyOnLeft().put(7, "x"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - diff1.entriesOnlyOnRight().put(7, "x"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> diff1.entriesInCommon().put(7, "x")); + assertThrows(UnsupportedOperationException.class, () -> diff1.entriesOnlyOnLeft().put(7, "x")); + assertThrows(UnsupportedOperationException.class, () -> diff1.entriesOnlyOnRight().put(7, "x")); } public void testSortedMapDifferenceEquals() { @@ -766,26 +745,11 @@ public void testAsMapSortedWritesThrough() { public void testAsMapSortedSubViewKeySetsDoNotSupportAdd() { SortedMap map = Maps.asMap(new NonNavigableSortedSet(), LENGTH_FUNCTION); - try { - map.subMap("a", "z").keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.tailMap("a").keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.headMap("r").keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.headMap("r").tailMap("m").keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.subMap("a", "z").keySet().add("a")); + assertThrows(UnsupportedOperationException.class, () -> map.tailMap("a").keySet().add("a")); + assertThrows(UnsupportedOperationException.class, () -> map.headMap("r").keySet().add("a")); + assertThrows( + UnsupportedOperationException.class, () -> map.headMap("r").tailMap("m").keySet().add("a")); } public void testAsMapSortedEmpty() { @@ -892,31 +856,17 @@ public void testAsMapNavigableWritesThrough() { @GwtIncompatible // NavigableMap public void testAsMapNavigableSubViewKeySetsDoNotSupportAdd() { NavigableMap map = Maps.asMap(Sets.newTreeSet(), LENGTH_FUNCTION); - try { - map.descendingKeySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.subMap("a", true, "z", false).keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.tailMap("a", true).keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.headMap("r", true).keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.headMap("r", false).tailMap("m", true).keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.descendingKeySet().add("a")); + assertThrows( + UnsupportedOperationException.class, + () -> map.subMap("a", true, "z", false).keySet().add("a")); + assertThrows( + UnsupportedOperationException.class, () -> map.tailMap("a", true).keySet().add("a")); + assertThrows( + UnsupportedOperationException.class, () -> map.headMap("r", true).keySet().add("a")); + assertThrows( + UnsupportedOperationException.class, + () -> map.headMap("r", false).tailMap("m", true).keySet().add("a")); } @GwtIncompatible // NavigableMap @@ -957,20 +907,14 @@ public void testToMapWithDuplicateKeys() { public void testToMapWithNullKeys() { Iterable<@Nullable String> strings = Arrays.asList("one", null, "three"); - try { - Maps.toMap((Iterable) strings, Functions.constant("foo")); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Maps.toMap((Iterable) strings, Functions.constant("foo"))); } public void testToMapWithNullValues() { Iterable strings = ImmutableList.of("one", "two", "three"); - try { - Maps.toMap(strings, Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Maps.toMap(strings, Functions.constant(null))); } private static final ImmutableBiMap INT_TO_STRING_MAP = @@ -1008,33 +952,27 @@ public void testUniqueIndexIterator() { /** Can't create the map if more than one value maps to the same key. */ public void testUniqueIndexDuplicates() { - try { - Map unused = - Maps.uniqueIndex(ImmutableSet.of("one", "uno"), Functions.constant(1)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("Multimaps.index"); - } + IllegalArgumentException expected = + assertThrows( + IllegalArgumentException.class, + () -> Maps.uniqueIndex(ImmutableSet.of("one", "uno"), Functions.constant(1))); + assertThat(expected.getMessage()).contains("Multimaps.index"); } /** Null values are not allowed. */ public void testUniqueIndexNullValue() { List<@Nullable String> listWithNull = Lists.newArrayList((String) null); - try { - Maps.uniqueIndex((List) listWithNull, Functions.constant(1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Maps.uniqueIndex((List) listWithNull, Functions.constant(1))); } /** Null keys aren't allowed either. */ public void testUniqueIndexNullKey() { List oneStringList = Lists.newArrayList("foo"); - try { - Maps.uniqueIndex(oneStringList, Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Maps.uniqueIndex(oneStringList, Functions.constant(null))); } @J2ktIncompatible @@ -1101,11 +1039,7 @@ public Enumeration propertyNames() { properties.setProperty("first", "true"); properties.setProperty("second", "null"); - try { - Maps.fromProperties(properties); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Maps.fromProperties(properties)); } @J2ktIncompatible @@ -1121,11 +1055,7 @@ public Enumeration propertyNames() { } }; - try { - Maps.fromProperties(properties); - fail(); - } catch (ClassCastException expected) { - } + assertThrows(ClassCastException.class, () -> Maps.fromProperties(properties)); } public void testAsConverter_nominal() throws Exception { @@ -1156,11 +1086,7 @@ public void testAsConverter_noMapping() throws Exception { "one", 1, "two", 2); Converter converter = Maps.asConverter(biMap); - try { - converter.convert("three"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> converter.convert("three")); } public void testAsConverter_nullConversions() throws Exception { @@ -1181,11 +1107,7 @@ public void testAsConverter_isAView() throws Exception { assertEquals((Integer) 1, converter.convert("one")); assertEquals((Integer) 2, converter.convert("two")); - try { - converter.convert("three"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> converter.convert("three")); biMap.put("three", 3); @@ -1199,11 +1121,9 @@ public void testAsConverter_withNullMapping() throws Exception { biMap.put("one", 1); biMap.put("two", 2); biMap.put("three", null); - try { - Maps.asConverter((BiMap) biMap).convert("three"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Maps.asConverter((BiMap) biMap).convert("three")); } public void testAsConverter_toString() { @@ -1242,70 +1162,34 @@ public void testUnmodifiableBiMap() { assertEquals(true, unmod.inverse().get("four").equals(4)); /* UnsupportedOperationException on direct modifications. */ - try { - unmod.put(4, "four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.forcePut(4, "four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.putAll(Collections.singletonMap(4, "four")); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> unmod.put(4, "four")); + assertThrows(UnsupportedOperationException.class, () -> unmod.forcePut(4, "four")); + assertThrows( + UnsupportedOperationException.class, + () -> unmod.putAll(Collections.singletonMap(4, "four"))); /* UnsupportedOperationException on indirect modifications. */ BiMap inverse = unmod.inverse(); - try { - inverse.put("four", 4); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - inverse.forcePut("four", 4); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - inverse.putAll(Collections.singletonMap("four", 4)); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> inverse.put("four", 4)); + assertThrows(UnsupportedOperationException.class, () -> inverse.forcePut("four", 4)); + assertThrows( + UnsupportedOperationException.class, + () -> inverse.putAll(Collections.singletonMap("four", 4))); Set values = unmod.values(); - try { - values.remove("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> values.remove("four")); Set> entries = unmod.entrySet(); Entry entry = entries.iterator().next(); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); @SuppressWarnings("unchecked") Entry entry2 = (Entry) entries.toArray()[0]; - try { - entry2.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> entry2.setValue("four")); } public void testImmutableEntry() { Entry e = Maps.immutableEntry("foo", 1); assertEquals("foo", e.getKey()); assertEquals(1, (int) e.getValue()); - try { - e.setValue(2); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> e.setValue(2)); assertEquals("foo=1", e.toString()); assertEquals(101575, e.hashCode()); } @@ -1315,11 +1199,7 @@ public void testImmutableEntryNull() { Maps.immutableEntry((String) null, (Integer) null); assertNull(e.getKey()); assertNull(e.getValue()); - try { - e.setValue(null); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> e.setValue(null)); assertEquals("null=null", e.toString()); assertEquals(0, e.hashCode()); } @@ -1512,92 +1392,64 @@ public void testUnmodifiableNavigableMap() { ensureNotDirectlyModifiable(unmod.tailMap(2, true)); Collection values = unmod.values(); - try { - values.add("4"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - values.remove("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - values.removeAll(Collections.singleton("four")); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - values.retainAll(Collections.singleton("four")); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - Iterator iterator = values.iterator(); - iterator.next(); - iterator.remove(); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> values.add("4")); + assertThrows(UnsupportedOperationException.class, () -> values.remove("four")); + assertThrows( + UnsupportedOperationException.class, () -> values.removeAll(Collections.singleton("four"))); + assertThrows( + UnsupportedOperationException.class, () -> values.retainAll(Collections.singleton("four"))); + assertThrows( + UnsupportedOperationException.class, + () -> { + Iterator iterator = values.iterator(); + iterator.next(); + iterator.remove(); + }); Set> entries = unmod.entrySet(); - try { - Iterator> iterator = entries.iterator(); - iterator.next(); - iterator.remove(); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, + () -> { + Iterator> iterator = entries.iterator(); + iterator.next(); + iterator.remove(); + }); + { Entry entry = entries.iterator().next(); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.lowerEntry(1); + { + Entry entry = unmod.lowerEntry(1); assertNull(entry); - entry = unmod.floorEntry(2); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { } - entry = unmod.ceilingEntry(2); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.floorEntry(2); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.lowerEntry(2); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.ceilingEntry(2); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.higherEntry(2); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.lowerEntry(2); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.firstEntry(); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.higherEntry(2); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.lastEntry(); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.firstEntry(); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - @SuppressWarnings("unchecked") - Entry entry2 = (Entry) entries.toArray()[0]; - try { - entry2.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.lastEntry(); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); + } + { + @SuppressWarnings("unchecked") + Entry entry = (Entry) entries.toArray()[0]; + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } } @@ -1705,11 +1557,7 @@ public void testSubMap_unnaturalOrdering() { .put(10, 0) .build(); - try { - Maps.subMap(map, Range.closed(4, 8)); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Maps.subMap(map, Range.closed(4, 8))); // These results are all incorrect, but there's no way (short of iterating over the result) // to verify that with an arbitrary ordering or comparator. diff --git a/android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java b/android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java index 3583c5675848..f83afa1837a1 100644 --- a/android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java +++ b/android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -196,23 +198,13 @@ public void testTransformIdentityFunctionEquality() { public void testTransformPutEntryIsUnsupported() { Map map = Maps.transformValues(ImmutableMap.of("a", 1), Functions.toStringFunction()); - try { - map.put("b", "2"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.put("b", "2")); - try { - map.putAll(ImmutableMap.of("b", "2")); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.putAll(ImmutableMap.of("b", "2"))); - try { - map.entrySet().iterator().next().setValue("one"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, + () -> map.entrySet().iterator().next().setValue("one")); } public void testTransformRemoveEntry() { diff --git a/android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java b/android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java index ca19020ab9fd..2edc6043f892 100644 --- a/android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java +++ b/android/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java @@ -19,6 +19,7 @@ import static com.google.common.base.Objects.equal; import static com.google.common.collect.Platform.reduceExponentIfGwt; import static com.google.common.collect.Platform.reduceIterationsIfGwt; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -326,11 +327,7 @@ public void testIteratorPastEndException() { assertTrue("Iterator has reached end prematurely", it.hasNext()); it.next(); it.next(); - try { - it.next(); - fail("No exception thrown when iterating past end of heap"); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> it.next()); } public void testIteratorConcurrentModification() { @@ -341,11 +338,7 @@ public void testIteratorConcurrentModification() { it.next(); it.next(); mmHeap.remove(4); - try { - it.next(); - fail("No exception thrown when iterating a modified heap"); - } catch (ConcurrentModificationException expected) { - } + assertThrows(ConcurrentModificationException.class, () -> it.next()); } /** Tests a failure caused by fix to childless uncle issue. */ @@ -879,26 +872,12 @@ public void testIsEvenLevel() { // since isEvenLevel adds 1, we need to do - 2. assertTrue(MinMaxPriorityQueue.isEvenLevel((1 << 31) - 2)); assertTrue(MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE - 1)); - try { - MinMaxPriorityQueue.isEvenLevel((1 << 31) - 1); - fail("Should overflow"); - } catch (IllegalStateException expected) { - } - try { - MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE); - fail("Should overflow"); - } catch (IllegalStateException expected) { - } - try { - MinMaxPriorityQueue.isEvenLevel(1 << 31); - fail("Should be negative"); - } catch (IllegalStateException expected) { - } - try { - MinMaxPriorityQueue.isEvenLevel(Integer.MIN_VALUE); - fail("Should be negative"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel((1 << 31) - 1)); + assertThrows( + IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE)); + assertThrows(IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel(1 << 31)); + assertThrows( + IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel(Integer.MIN_VALUE)); } @J2ktIncompatible diff --git a/android/guava-tests/test/com/google/common/collect/MultimapsTest.java b/android/guava-tests/test/com/google/common/collect/MultimapsTest.java index 171f7a48687e..187f1997e9b4 100644 --- a/android/guava-tests/test/com/google/common/collect/MultimapsTest.java +++ b/android/guava-tests/test/com/google/common/collect/MultimapsTest.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Maps.immutableEntry; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.testing.Helpers.nefariousMapEntry; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; @@ -243,25 +244,13 @@ public void testUnmodifiableMultimapEntries() { Multimap mod = HashMultimap.create(); Multimap unmod = Multimaps.unmodifiableMultimap(mod); mod.put("foo", 1); - Entry entry = unmod.entries().iterator().next(); - try { - entry.setValue(2); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - entry = (Entry) unmod.entries().toArray()[0]; - try { - entry.setValue(2); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + Entry fromIterator = unmod.entries().iterator().next(); + assertThrows(UnsupportedOperationException.class, () -> fromIterator.setValue(2)); + Entry fromToArray = (Entry) unmod.entries().toArray()[0]; + assertThrows(UnsupportedOperationException.class, () -> fromToArray.setValue(2)); Entry[] array = (Entry[]) new Entry[2]; assertSame(array, unmod.entries().toArray(array)); - try { - array[0].setValue(2); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> array[0].setValue(2)); assertFalse(unmod.entries().contains(nefariousMapEntry("pwnd", 2))); assertFalse(unmod.keys().contains("pwnd")); } @@ -427,26 +416,14 @@ public void testForMap() { assertTrue(multimapView.containsEntry("bar", 2)); assertEquals(Collections.singleton(1), multimapView.get("foo")); assertEquals(Collections.singleton(2), multimapView.get("bar")); - try { - multimapView.put("baz", 3); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - multimapView.putAll("baz", Collections.singleton(3)); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - multimapView.putAll(multimap); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - multimapView.replaceValues("foo", Collections.emptySet()); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> multimapView.put("baz", 3)); + assertThrows( + UnsupportedOperationException.class, + () -> multimapView.putAll("baz", Collections.singleton(3))); + assertThrows(UnsupportedOperationException.class, () -> multimapView.putAll(multimap)); + assertThrows( + UnsupportedOperationException.class, + () -> multimapView.replaceValues("foo", Collections.emptySet())); multimapView.remove("bar", 2); assertFalse(multimapView.containsKey("bar")); assertFalse(map.containsKey("bar")); @@ -599,18 +576,10 @@ public boolean addAll(Collection collection) { Map> map = Maps.newEnumMap(Color.class); Multimap multimap = Multimaps.newMultimap(map, factory); - try { - multimap.put(Color.BLUE, -1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> multimap.put(Color.BLUE, -1)); multimap.put(Color.RED, 1); multimap.put(Color.BLUE, 2); - try { - multimap.put(Color.GREEN, -1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> multimap.put(Color.GREEN, -1)); assertThat(multimap.entries()) .containsExactly(Maps.immutableEntry(Color.RED, 1), Maps.immutableEntry(Color.BLUE, 2)); } @@ -823,20 +792,15 @@ public Integer apply(String input) { public void testIndex_nullValue() { List<@Nullable Integer> values = Arrays.asList(1, null); - try { - Multimaps.index((List) values, Functions.identity()); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Multimaps.index((List) values, Functions.identity())); } public void testIndex_nullKey() { List values = Arrays.asList(1, 2); - try { - Multimaps.index(values, Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> Multimaps.index(values, Functions.constant(null))); } @GwtIncompatible(value = "untested") @@ -970,11 +934,8 @@ public void testFilteredKeysSetMultimapReplaceValues() { assertEquals(ImmutableSet.of(), filtered.replaceValues("baz", ImmutableSet.of())); - try { - filtered.replaceValues("baz", ImmutableSet.of(5)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> filtered.replaceValues("baz", ImmutableSet.of(5))); } public void testFilteredKeysSetMultimapGetBadValue() { @@ -988,16 +949,8 @@ public void testFilteredKeysSetMultimapGetBadValue() { Multimaps.filterKeys(multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); Set bazSet = filtered.get("baz"); assertThat(bazSet).isEmpty(); - try { - bazSet.add(5); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - try { - bazSet.addAll(ImmutableSet.of(6, 7)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> bazSet.add(5)); + assertThrows(IllegalArgumentException.class, () -> bazSet.addAll(ImmutableSet.of(6, 7))); } public void testFilteredKeysListMultimapGetBadValue() { @@ -1011,26 +964,10 @@ public void testFilteredKeysListMultimapGetBadValue() { Multimaps.filterKeys(multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); List bazList = filtered.get("baz"); assertThat(bazList).isEmpty(); - try { - bazList.add(5); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - try { - bazList.add(0, 6); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - try { - bazList.addAll(ImmutableList.of(7, 8)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - try { - bazList.addAll(0, ImmutableList.of(9, 10)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> bazList.add(5)); + assertThrows(IllegalArgumentException.class, () -> bazList.add(0, 6)); + assertThrows(IllegalArgumentException.class, () -> bazList.addAll(ImmutableList.of(7, 8))); + assertThrows(IllegalArgumentException.class, () -> bazList.addAll(0, ImmutableList.of(9, 10))); } @J2ktIncompatible diff --git a/android/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java b/android/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java index 792520f8881b..447fffbce795 100644 --- a/android/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java +++ b/android/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset.Entry; import java.util.Collections; @@ -77,10 +79,6 @@ public void testHashCodeNull() { } public void testNegativeCount() { - try { - entry("foo", -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> entry("foo", -1)); } } diff --git a/android/guava-tests/test/com/google/common/collect/OrderingTest.java b/android/guava-tests/test/com/google/common/collect/OrderingTest.java index d0d65662f5c3..51ae6bac5b5b 100644 --- a/android/guava-tests/test/com/google/common/collect/OrderingTest.java +++ b/android/guava-tests/test/com/google/common/collect/OrderingTest.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static com.google.common.truth.Truth.assertThat; @@ -111,21 +112,9 @@ public void testComplicatedOrderingExample() { public void testNatural() { Ordering comparator = Ordering.natural(); Helpers.testComparator(comparator, Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE); - try { - comparator.compare(1, null); - fail(); - } catch (NullPointerException expected) { - } - try { - comparator.compare(null, 2); - fail(); - } catch (NullPointerException expected) { - } - try { - comparator.compare(null, null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> comparator.compare(1, null)); + assertThrows(NullPointerException.class, () -> comparator.compare(null, 2)); + assertThrows(NullPointerException.class, () -> comparator.compare(null, null)); assertSame(comparator, reserialize(comparator)); assertEquals("Ordering.natural()", comparator.toString()); } @@ -146,24 +135,18 @@ public void testFrom() { public void testExplicit_none() { Comparator c = Ordering.explicit(Collections.emptyList()); - try { - c.compare(0, 0); - fail(); - } catch (IncomparableValueException expected) { - assertEquals(0, expected.value); - } + IncomparableValueException expected = + assertThrows(IncomparableValueException.class, () -> c.compare(0, 0)); + assertEquals(0, expected.value); reserializeAndAssert(c); } public void testExplicit_one() { Comparator c = Ordering.explicit(0); assertEquals(0, c.compare(0, 0)); - try { - c.compare(0, 1); - fail(); - } catch (IncomparableValueException expected) { - assertEquals(1, expected.value); - } + IncomparableValueException expected = + assertThrows(IncomparableValueException.class, () -> c.compare(0, 1)); + assertEquals(1, expected.value); reserializeAndAssert(c); assertEquals("Ordering.explicit([0])", c.toString()); } @@ -173,12 +156,9 @@ public void testExplicitMax_b297601553() { // TODO(b/297601553): this should probably throw an CCE since 0 isn't explicitly listed assertEquals(0, (int) c.max(asList(0))); - try { - c.max(asList(0, 1)); - fail(); - } catch (IncomparableValueException expected) { - assertEquals(0, expected.value); - } + IncomparableValueException expected = + assertThrows(IncomparableValueException.class, () -> c.max(asList(0, 1))); + assertEquals(0, expected.value); } public void testExplicit_two() { @@ -186,12 +166,9 @@ public void testExplicit_two() { assertEquals(0, c.compare(5, 5)); assertTrue(c.compare(5, 42) > 0); assertTrue(c.compare(42, 5) < 0); - try { - c.compare(5, 666); - fail(); - } catch (IncomparableValueException expected) { - assertEquals(666, expected.value); - } + IncomparableValueException expected = + assertThrows(IncomparableValueException.class, () -> c.compare(5, 666)); + assertEquals(666, expected.value); new EqualsTester() .addEqualityGroup(c, Ordering.explicit(42, 5)) .addEqualityGroup(Ordering.explicit(5, 42)) @@ -210,11 +187,7 @@ public void testExplicit_sortingExample() { @SuppressWarnings("DistinctVarargsChecker") // test of buggy call public void testExplicit_withDuplicates() { - try { - Ordering.explicit(1, 2, 3, 4, 2); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ordering.explicit(1, 2, 3, 4, 2)); } // A more limited test than the one that follows, but this one uses the @@ -486,11 +459,12 @@ public void testImmutableSortedCopy() { numberOrdering.immutableSortedCopy(Collections.emptyList())); List<@Nullable Integer> listWithNull = Arrays.asList(5, 3, null, 9); - try { - Ordering.natural().nullsFirst().immutableSortedCopy((List) listWithNull); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> + Ordering.natural() + .nullsFirst() + .immutableSortedCopy((List) listWithNull)); } public void testIsOrdered() { @@ -542,19 +516,15 @@ public void testLeastOfIterator_empty_1() { } public void testLeastOfIterable_simple_negativeOne() { - try { - numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), -1)); } public void testLeastOfIterator_simple_negativeOne() { - try { - numberOrdering.leastOf(Iterators.forArray(3, 4, 5, -1), -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> numberOrdering.leastOf(Iterators.forArray(3, 4, 5, -1), -1)); } public void testLeastOfIterable_singleton_0() { diff --git a/android/guava-tests/test/com/google/common/collect/PeekingIteratorTest.java b/android/guava-tests/test/com/google/common/collect/PeekingIteratorTest.java index 22686633c6ae..508ee8efc10c 100644 --- a/android/guava-tests/test/com/google/common/collect/PeekingIteratorTest.java +++ b/android/guava-tests/test/com/google/common/collect/PeekingIteratorTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Iterators.peekingIterator; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static java.util.Collections.emptyList; @@ -114,12 +115,7 @@ public void testPeekOnEmptyList() { Iterator iterator = list.iterator(); PeekingIterator peekingIterator = Iterators.peekingIterator(iterator); - try { - peekingIterator.peek(); - fail("Should throw NoSuchElementException if nothing to peek()"); - } catch (NoSuchElementException e) { - /* expected */ - } + assertThrows(NoSuchElementException.class, () -> peekingIterator.peek()); } public void testPeekDoesntChangeIteration() { @@ -145,24 +141,9 @@ public void testPeekDoesntChangeIteration() { assertEquals( "next() should still return last element after peeking", "C", peekingIterator.next()); - try { - peekingIterator.peek(); - fail("Should throw exception if no next to peek()"); - } catch (NoSuchElementException e) { - /* expected */ - } - try { - peekingIterator.peek(); - fail("Should continue to throw exception if no next to peek()"); - } catch (NoSuchElementException e) { - /* expected */ - } - try { - peekingIterator.next(); - fail("next() should still throw exception after the end of iteration"); - } catch (NoSuchElementException e) { - /* expected */ - } + assertThrows(NoSuchElementException.class, () -> peekingIterator.peek()); + assertThrows(NoSuchElementException.class, () -> peekingIterator.peek()); + assertThrows(NoSuchElementException.class, () -> peekingIterator.next()); } public void testCantRemoveAfterPeek() { @@ -174,12 +155,7 @@ public void testCantRemoveAfterPeek() { assertEquals("B", peekingIterator.peek()); /* Should complain on attempt to remove() after peek(). */ - try { - peekingIterator.remove(); - fail("remove() should throw IllegalStateException after a peek()"); - } catch (IllegalStateException e) { - /* expected */ - } + assertThrows(IllegalStateException.class, () -> peekingIterator.remove()); assertEquals( "After remove() throws exception, peek should still be ok", "B", peekingIterator.peek()); diff --git a/android/guava-tests/test/com/google/common/collect/RangeTest.java b/android/guava-tests/test/com/google/common/collect/RangeTest.java index 7ea3b0bed73e..ffd73e0886f5 100644 --- a/android/guava-tests/test/com/google/common/collect/RangeTest.java +++ b/android/guava-tests/test/com/google/common/collect/RangeTest.java @@ -19,6 +19,7 @@ import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.DiscreteDomain.integers; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -58,16 +59,8 @@ public void testOpen() { } public void testOpen_invalid() { - try { - Range.open(4, 3); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - Range.open(3, 3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.open(4, 3)); + assertThrows(IllegalArgumentException.class, () -> Range.open(3, 3)); } public void testClosed() { @@ -85,11 +78,7 @@ public void testClosed() { } public void testClosed_invalid() { - try { - Range.closed(4, 3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.closed(4, 3)); } public void testOpenClosed() { @@ -294,6 +283,7 @@ public void testOrderingCuts() { Helpers.testCompareToAndEquals(ImmutableList.of(a, b, c, d, e, f)); } + @SuppressWarnings("DistinctVarargsChecker") public void testContainsAll() { Range range = Range.closed(3, 5); assertTrue(range.containsAll(asList(3, 3, 4, 5))); @@ -348,43 +338,35 @@ public void testIntersection_empty() { Range range = Range.closedOpen(3, 3); assertEquals(range, range.intersection(range)); - try { - range.intersection(Range.open(3, 5)); - fail(); - } catch (IllegalArgumentException expected) { - // TODO(kevinb): convert the rest of this file to Truth someday - assertThat(expected).hasMessageThat().contains("connected"); - } - try { - range.intersection(Range.closed(0, 2)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.open(3, 5))); + assertThat(expected).hasMessageThat().contains("connected"); + expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.closed(0, 2))); + assertThat(expected).hasMessageThat().contains("connected"); } public void testIntersection_deFactoEmpty() { - Range range = Range.open(3, 4); - assertEquals(range, range.intersection(range)); + { + Range range = Range.open(3, 4); + assertEquals(range, range.intersection(range)); - assertEquals(Range.openClosed(3, 3), range.intersection(Range.atMost(3))); - assertEquals(Range.closedOpen(4, 4), range.intersection(Range.atLeast(4))); + assertEquals(Range.openClosed(3, 3), range.intersection(Range.atMost(3))); + assertEquals(Range.closedOpen(4, 4), range.intersection(Range.atLeast(4))); - try { - range.intersection(Range.lessThan(3)); - fail(); - } catch (IllegalArgumentException expected) { + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.lessThan(3))); assertThat(expected).hasMessageThat().contains("connected"); - } - try { - range.intersection(Range.greaterThan(4)); - fail(); - } catch (IllegalArgumentException expected) { + expected = + assertThrows( + IllegalArgumentException.class, () -> range.intersection(Range.greaterThan(4))); assertThat(expected).hasMessageThat().contains("connected"); } - range = Range.closed(3, 4); - assertEquals(Range.openClosed(4, 4), range.intersection(Range.greaterThan(4))); + { + Range range = Range.closed(3, 4); + assertEquals(Range.openClosed(4, 4), range.intersection(Range.greaterThan(4))); + } } public void testIntersection_singleton() { @@ -399,30 +381,21 @@ public void testIntersection_singleton() { assertEquals(Range.closedOpen(3, 3), range.intersection(Range.lessThan(3))); assertEquals(Range.openClosed(3, 3), range.intersection(Range.greaterThan(3))); - try { - range.intersection(Range.atLeast(4)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } - try { - range.intersection(Range.atMost(2)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.atLeast(4))); + assertThat(expected).hasMessageThat().contains("connected"); + expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.atMost(2))); + assertThat(expected).hasMessageThat().contains("connected"); } public void testIntersection_general() { Range range = Range.closed(4, 8); // separate below - try { - range.intersection(Range.closed(0, 2)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.closed(0, 2))); + assertThat(expected).hasMessageThat().contains("connected"); // adjacent below assertEquals(Range.closedOpen(4, 4), range.intersection(Range.closedOpen(2, 4))); @@ -458,58 +431,28 @@ public void testIntersection_general() { assertEquals(Range.openClosed(8, 8), range.intersection(Range.openClosed(8, 10))); // separate above - try { - range.intersection(Range.closed(10, 12)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } + expected = + assertThrows( + IllegalArgumentException.class, () -> range.intersection(Range.closed(10, 12))); + assertThat(expected).hasMessageThat().contains("connected"); } public void testGap_overlapping() { Range range = Range.closedOpen(3, 5); - try { - range.gap(Range.closed(4, 6)); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - range.gap(Range.closed(2, 4)); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - range.gap(Range.closed(2, 3)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> range.gap(Range.closed(4, 6))); + assertThrows(IllegalArgumentException.class, () -> range.gap(Range.closed(2, 4))); + assertThrows(IllegalArgumentException.class, () -> range.gap(Range.closed(2, 3))); } public void testGap_invalidRangesWithInfinity() { - try { - Range.atLeast(1).gap(Range.atLeast(2)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.atLeast(1).gap(Range.atLeast(2))); - try { - Range.atLeast(2).gap(Range.atLeast(1)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.atLeast(2).gap(Range.atLeast(1))); - try { - Range.atMost(1).gap(Range.atMost(2)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.atMost(1).gap(Range.atMost(2))); - try { - Range.atMost(2).gap(Range.atMost(1)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.atMost(2).gap(Range.atMost(1))); } public void testGap_connectedAdjacentYieldsEmpty() { @@ -668,26 +611,14 @@ public void testEncloseAll() { } public void testEncloseAll_empty() { - try { - Range.encloseAll(ImmutableSet.of()); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> Range.encloseAll(ImmutableSet.of())); } public void testEncloseAll_nullValue() { List<@Nullable Integer> nullFirst = Lists.newArrayList(null, 0); - try { - Range.encloseAll((List) nullFirst); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Range.encloseAll((List) nullFirst)); List<@Nullable Integer> nullNotFirst = Lists.newArrayList(0, null); - try { - Range.encloseAll((List) nullNotFirst); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Range.encloseAll((List) nullNotFirst)); } public void testEquivalentFactories() { diff --git a/android/guava-tests/test/com/google/common/collect/ReflectionFreeAssertThrows.java b/android/guava-tests/test/com/google/common/collect/ReflectionFreeAssertThrows.java new file mode 100644 index 000000000000..e24b5b1027b9 --- /dev/null +++ b/android/guava-tests/test/com/google/common/collect/ReflectionFreeAssertThrows.java @@ -0,0 +1,160 @@ +/* + * 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.collect; + +import com.google.common.annotations.GwtCompatible; +import com.google.common.annotations.GwtIncompatible; +import com.google.common.annotations.J2ktIncompatible; +import com.google.common.base.Predicate; +import com.google.common.base.VerifyException; +import com.google.common.collect.Ordering.IncomparableValueException; +import com.google.common.collect.TestExceptions.SomeCheckedException; +import com.google.common.collect.TestExceptions.SomeError; +import com.google.common.collect.TestExceptions.SomeOtherCheckedException; +import com.google.common.collect.TestExceptions.SomeUncheckedException; +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(IncomparableValueException.class, e -> e instanceof IncomparableValueException) + .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/collect/SetsTest.java b/android/guava-tests/test/com/google/common/collect/SetsTest.java index 4505f9be37a1..dea8516cbb08 100644 --- a/android/guava-tests/test/com/google/common/collect/SetsTest.java +++ b/android/guava-tests/test/com/google/common/collect/SetsTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Iterables.unmodifiableIterable; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newEnumSet; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; @@ -335,16 +336,8 @@ public void testImmutableEnumSet() { Set units = Sets.immutableEnumSet(SomeEnum.D, SomeEnum.B); assertThat(units).containsExactly(SomeEnum.B, SomeEnum.D).inOrder(); - try { - units.remove(SomeEnum.B); - fail("ImmutableEnumSet should throw an exception on remove()"); - } catch (UnsupportedOperationException expected) { - } - try { - units.add(SomeEnum.C); - fail("ImmutableEnumSet should throw an exception on add()"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> units.remove(SomeEnum.B)); + assertThrows(UnsupportedOperationException.class, () -> units.add(SomeEnum.C)); } @J2ktIncompatible @@ -648,11 +641,7 @@ public void testComplementOfEmptyEnumSetWithoutType() { @GwtIncompatible // complementOf public void testComplementOfEmptySetWithoutTypeDoesntWork() { Set set = Collections.emptySet(); - try { - Sets.complementOf(set); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Sets.complementOf(set)); } @J2ktIncompatible @@ -682,11 +671,7 @@ public void testNewSetFromMapSerialization() { public void testNewSetFromMapIllegal() { Map map = new LinkedHashMap<>(); map.put(2, true); - try { - Sets.newSetFromMap(map); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Sets.newSetFromMap(map)); } /** The 0-ary cartesian product is a single empty list. */ @@ -790,11 +775,8 @@ public void testCartesianProduct_unrelatedTypes() { public void testCartesianProductTooBig() { Set set = ContiguousSet.create(Range.closed(0, 10000), DiscreteDomain.integers()); - try { - Sets.cartesianProduct(set, set, set, set, set); - fail("Expected IAE"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> Sets.cartesianProduct(set, set, set, set, set)); } public void testCartesianProduct_hashCode() { @@ -879,11 +861,7 @@ public void testPowerSetIteration_manual() { assertEquals(ImmutableSet.of(3, 2), i.next()); assertEquals(ImmutableSet.of(3, 2, 1), i.next()); assertFalse(i.hasNext()); - try { - i.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> i.next()); } @GwtIncompatible // too slow for GWT @@ -935,27 +913,24 @@ public void testPowerSetSize() { } public void testPowerSetCreationErrors() { - try { - Set> unused = - powerSet( - newHashSet( - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', - 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5')); - fail(); - } catch (IllegalArgumentException expected) { - } - - try { - Set> unused = powerSet(ContiguousSet.closed(0, Integer.MAX_VALUE / 2)); - fail(); - } catch (IllegalArgumentException expected) { - } - - try { - powerSet(singleton(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> { + Set> unused = + powerSet( + newHashSet( + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', + '5')); + }); + + assertThrows( + IllegalArgumentException.class, + () -> { + Set> unused = powerSet(ContiguousSet.closed(0, Integer.MAX_VALUE / 2)); + }); + + assertThrows(NullPointerException.class, () -> powerSet(singleton(null))); } public void testPowerSetEqualsAndHashCode_verifyAgainstHashSet() { @@ -1152,21 +1127,10 @@ public void testUnmodifiableNavigableSet() { /* UnsupportedOperationException on indirect modifications. */ NavigableSet reverse = unmod.descendingSet(); - try { - reverse.add(4); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - reverse.addAll(Collections.singleton(4)); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - reverse.remove(4); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> reverse.add(4)); + assertThrows( + UnsupportedOperationException.class, () -> reverse.addAll(Collections.singleton(4))); + assertThrows(UnsupportedOperationException.class, () -> reverse.remove(4)); } void ensureNotDirectlyModifiable(SortedSet unmod) { @@ -1305,11 +1269,7 @@ public void testSubSet_unnaturalOrdering() { ImmutableSortedSet set = ImmutableSortedSet.reverseOrder().add(2, 4, 6, 8, 10).build(); - try { - Sets.subSet(set, Range.closed(4, 8)); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Sets.subSet(set, Range.closed(4, 8))); // These results are all incorrect, but there's no way (short of iterating over the result) // to verify that with an arbitrary ordering or comparator. diff --git a/android/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java b/android/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java index d7a281ae8e33..7dd66df559da 100644 --- a/android/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java +++ b/android/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java @@ -15,6 +15,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -68,6 +69,7 @@ protected Multiset create(String[] elements) { return suite; } + @SuppressWarnings("ModifiedButNotUsed") public void testFastAddAllMultiset() { final AtomicInteger addCalls = new AtomicInteger(); Multiset multiset = @@ -87,11 +89,7 @@ public int add(String element, int occurrences) { public void testRemoveUnsupported() { Multiset multiset = new NoRemoveMultiset<>(); multiset.add("a"); - try { - multiset.remove("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> multiset.remove("a")); assertTrue(multiset.contains("a")); } diff --git a/android/guava-tests/test/com/google/common/collect/TableCollectionTest.java b/android/guava-tests/test/com/google/common/collect/TableCollectionTest.java index 1a956f74c473..c12e3f77af09 100644 --- a/android/guava-tests/test/com/google/common/collect/TableCollectionTest.java +++ b/android/guava-tests/test/com/google/common/collect/TableCollectionTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -853,11 +854,7 @@ public void testRemove() { assertFalse(map.containsKey(keyToRemove)); assertEquals(initialSize - 1, map.size()); } else { - try { - map.remove(keyToRemove); - fail("Expected UnsupportedOperationException."); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.remove(keyToRemove)); } assertInvariants(map); } diff --git a/android/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java index 8039b1dec5c1..23b802246754 100644 --- a/android/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java +++ b/android/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -61,11 +62,7 @@ public void testNullPointerInstance() {} // put() and putAll() aren't supported. @Override public void testPut() { - try { - table.put("foo", 1, 'a'); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> table.put("foo", 1, 'a')); assertSize(0); } @@ -76,11 +73,7 @@ public void testPutAllTable() { other.put("foo", 1, 'd'); other.put("bar", 2, 'e'); other.put("cat", 2, 'f'); - try { - table.putAll(other); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> table.putAll(other)); assertEquals((Character) 'a', table.get("foo", 1)); assertEquals((Character) 'b', table.get("bar", 1)); assertEquals((Character) 'c', table.get("foo", 3)); diff --git a/android/guava-tests/test/com/google/common/collect/TestExceptions.java b/android/guava-tests/test/com/google/common/collect/TestExceptions.java new file mode 100644 index 000000000000..f7ca37fbd944 --- /dev/null +++ b/android/guava-tests/test/com/google/common/collect/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.collect; + +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/collect/TopKSelectorTest.java b/android/guava-tests/test/com/google/common/collect/TopKSelectorTest.java index 05ecb2040fe4..9793dbd77e20 100644 --- a/android/guava-tests/test/com/google/common/collect/TopKSelectorTest.java +++ b/android/guava-tests/test/com/google/common/collect/TopKSelectorTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -36,26 +37,11 @@ public class TopKSelectorTest extends TestCase { public void testNegativeK() { - try { - TopKSelector.least(-1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - TopKSelector.greatest(-1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - TopKSelector.least(-1, Ordering.natural()); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - TopKSelector.greatest(-1, Ordering.natural()); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> TopKSelector.least(-1)); + assertThrows(IllegalArgumentException.class, () -> TopKSelector.greatest(-1)); + assertThrows(IllegalArgumentException.class, () -> TopKSelector.least(-1, Ordering.natural())); + assertThrows( + IllegalArgumentException.class, () -> TopKSelector.greatest(-1, Ordering.natural())); } public void testZeroK() { diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableIteratorTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableIteratorTest.java index e2e432fe5299..fad660a0c6f6 100644 --- a/android/guava-tests/test/com/google/common/collect/UnmodifiableIteratorTest.java +++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableIteratorTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.NoSuchElementException; @@ -54,10 +56,6 @@ public String next() { assertTrue(iterator.hasNext()); assertEquals("a", iterator.next()); - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); } } diff --git a/android/guava-tests/test/com/google/common/collect/UnmodifiableListIteratorTest.java b/android/guava-tests/test/com/google/common/collect/UnmodifiableListIteratorTest.java index 130ef6b7cdca..02cf78e2baa7 100644 --- a/android/guava-tests/test/com/google/common/collect/UnmodifiableListIteratorTest.java +++ b/android/guava-tests/test/com/google/common/collect/UnmodifiableListIteratorTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.ListIterator; @@ -36,11 +38,7 @@ public void testRemove() { assertTrue(iterator.hasNext()); assertEquals("a", iterator.next()); - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); } @SuppressWarnings("DoNotCall") @@ -51,11 +49,7 @@ public void testAdd() { assertEquals("a", iterator.next()); assertEquals("b", iterator.next()); assertEquals("b", iterator.previous()); - try { - iterator.add("c"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.add("c")); } @SuppressWarnings("DoNotCall") @@ -66,11 +60,7 @@ public void testSet() { assertEquals("a", iterator.next()); assertEquals("b", iterator.next()); assertEquals("b", iterator.previous()); - try { - iterator.set("c"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.set("c")); } UnmodifiableListIterator create() { diff --git a/guava-tests/test/com/google/common/collect/AbstractFilteredMapTest.java b/guava-tests/test/com/google/common/collect/AbstractFilteredMapTest.java index 068e1301e1e8..9dfa3fde21f6 100644 --- a/guava-tests/test/com/google/common/collect/AbstractFilteredMapTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractFilteredMapTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.base.Predicate; import com.google.common.base.Predicates; @@ -42,11 +44,7 @@ public void testFilteredKeysIllegalPut() { filtered.put("b", 2); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); - try { - filtered.put("yyy", 3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> filtered.put("yyy", 3)); } public void testFilteredKeysIllegalPutAll() { @@ -56,11 +54,9 @@ public void testFilteredKeysIllegalPutAll() { filtered.put("b", 2); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); - try { - filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> filtered.putAll(ImmutableMap.of("c", 3, "zzz", 4, "b", 5))); assertEquals(ImmutableMap.of("a", 1, "b", 2), filtered); } @@ -91,11 +87,7 @@ public void testFilteredValuesIllegalPut() { unfiltered.put("c", 5); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); - try { - filtered.put("yyy", 3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> filtered.put("yyy", 3)); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } @@ -107,11 +99,9 @@ public void testFilteredValuesIllegalPutAll() { unfiltered.put("c", 5); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); - try { - filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> filtered.putAll(ImmutableMap.of("c", 4, "zzz", 5, "b", 6))); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } @@ -123,11 +113,7 @@ public void testFilteredValuesIllegalSetValue() { assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); Entry entry = filtered.entrySet().iterator().next(); - try { - entry.setValue(5); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> entry.setValue(5)); assertEquals(ImmutableMap.of("a", 2, "b", 4), filtered); } @@ -158,11 +144,7 @@ public void testFilteredEntriesIllegalPut() { filtered.put("chicken", 7); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); - try { - filtered.put("cow", 7); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> filtered.put("cow", 7)); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); } @@ -177,11 +159,9 @@ public void testFilteredEntriesIllegalPutAll() { filtered.put("chicken", 7); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); - try { - filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> filtered.putAll(ImmutableMap.of("sheep", 5, "cow", 7))); assertEquals(ImmutableMap.of("cat", 3, "horse", 5, "chicken", 7), filtered); } diff --git a/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java b/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java index e87c42be38bc..c5716f94b159 100644 --- a/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractImmutableSetTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; @@ -132,20 +133,12 @@ public void testCopyOf_arrayOfOneElement() { } public void testCopyOf_nullArray() { - try { - copyOf((String[]) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> copyOf((String[]) null)); } public void testCopyOf_arrayContainingOnlyNull() { @Nullable String[] array = new @Nullable String[] {null}; - try { - copyOf((String[]) array); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> copyOf((String[]) array)); } public void testCopyOf_collection_empty() { @@ -178,11 +171,7 @@ public void testCopyOf_collection_general() { public void testCopyOf_collectionContainingNull() { Collection<@Nullable String> c = MinimalCollection.of("a", null, "b"); - try { - copyOf((Collection) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> copyOf((Collection) c)); } enum TestEnum { @@ -228,11 +217,7 @@ public void testCopyOf_iterator_general() { public void testCopyOf_iteratorContainingNull() { Iterator<@Nullable String> c = Iterators.forArray("a", null, "b"); - try { - copyOf((Iterator) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> copyOf((Iterator) c)); } private static class CountingIterable implements Iterable { @@ -398,76 +383,59 @@ public void testComplexBuilder() { abstract int getComplexBuilderSetLastElement(); public void testBuilderAddHandlesNullsCorrectly() { + { ImmutableSet.Builder builder = this.builder(); - try { - builder.add((String) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.add((String) null)); } - builder = this.builder(); - try { - builder.add((String[]) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add((String[]) null)); } - builder = this.builder(); - try { - builder.add("a", (String) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add("a", (String) null)); } - builder = this.builder(); - try { - builder.add("a", "b", (String) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add("a", "b", (String) null)); } - builder = this.builder(); - try { - builder.add("a", "b", "c", null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add("a", "b", "c", null)); } - builder = this.builder(); - try { - builder.add("a", "b", null, "c"); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.add("a", "b", null, "c")); } } public void testBuilderAddAllHandlesNullsCorrectly() { + { ImmutableSet.Builder builder = this.builder(); - try { - builder.addAll((Iterable) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((Iterable) null)); } - try { - builder.addAll((Iterator) null); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + { + ImmutableSet.Builder builder = this.builder(); + assertThrows(NullPointerException.class, () -> builder.addAll((Iterator) null)); } - builder = this.builder(); + { + ImmutableSet.Builder builder = this.builder(); List<@Nullable String> listWithNulls = asList("a", null, "b"); - try { - builder.addAll((List) listWithNulls); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((List) listWithNulls)); } + { + ImmutableSet.Builder builder = this.builder(); Iterable<@Nullable String> iterableWithNulls = MinimalIterable.of("a", null, "b"); - try { - builder.addAll((Iterable) iterableWithNulls); - fail("expected NullPointerException"); // COV_NF_LINE - } catch (NullPointerException expected) { + assertThrows( + NullPointerException.class, () -> builder.addAll((Iterable) iterableWithNulls)); } } diff --git a/guava-tests/test/com/google/common/collect/AbstractImmutableTableTest.java b/guava-tests/test/com/google/common/collect/AbstractImmutableTableTest.java index 8edd14f5d847..45f877a17ecf 100644 --- a/guava-tests/test/com/google/common/collect/AbstractImmutableTableTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractImmutableTableTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; @@ -32,45 +34,27 @@ public abstract class AbstractImmutableTableTest extends TestCase { public final void testClear() { for (Table testInstance : getTestInstances()) { - try { - testInstance.clear(); - fail(); - } catch (UnsupportedOperationException e) { - // success - } + assertThrows(UnsupportedOperationException.class, () -> testInstance.clear()); } } public final void testPut() { for (Table testInstance : getTestInstances()) { - try { - testInstance.put('a', 1, "blah"); - fail(); - } catch (UnsupportedOperationException e) { - // success - } + assertThrows(UnsupportedOperationException.class, () -> testInstance.put('a', 1, "blah")); } } public final void testPutAll() { for (Table testInstance : getTestInstances()) { - try { - testInstance.putAll(ImmutableTable.of('a', 1, "blah")); - fail(); - } catch (UnsupportedOperationException e) { - // success - } + assertThrows( + UnsupportedOperationException.class, + () -> testInstance.putAll(ImmutableTable.of('a', 1, "blah"))); } } public final void testRemove() { for (Table testInstance : getTestInstances()) { - try { - testInstance.remove('a', 1); - fail(); - } catch (UnsupportedOperationException e) { - // success - } + assertThrows(UnsupportedOperationException.class, () -> testInstance.remove('a', 1)); } } diff --git a/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java b/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java index 67ba8759d85d..1b6d6656483e 100644 --- a/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractIteratorTest.java @@ -16,9 +16,13 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; +import com.google.common.collect.TestExceptions.SomeCheckedException; +import com.google.common.collect.TestExceptions.SomeUncheckedException; import com.google.common.testing.GcFinalization; import java.lang.ref.WeakReference; import java.util.Iterator; @@ -73,11 +77,7 @@ public void testDefaultBehaviorOfNextAndHasNext() { // 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 testDefaultBehaviorOfPeek() { @@ -113,29 +113,14 @@ public void testDefaultBehaviorOfPeek() { assertEquals(1, (int) iter.peek()); assertEquals(1, (int) iter.next()); - try { - iter.peek(); - fail("peek() should throw NoSuchElementException at end"); - } catch (NoSuchElementException expected) { - } - - try { - iter.peek(); - fail("peek() should continue to throw NoSuchElementException at end"); - } catch (NoSuchElementException expected) { - } - - try { - iter.next(); - fail("next() should throw NoSuchElementException as usual"); - } catch (NoSuchElementException expected) { - } - - try { - iter.peek(); - fail("peek() should still throw NoSuchElementException after next()"); - } catch (NoSuchElementException expected) { - } + /* + * We test peek() after various calls to make sure that one bad call doesn't interfere with its + * ability to throw the correct exception in the future. + */ + assertThrows(NoSuchElementException.class, iter::peek); + assertThrows(NoSuchElementException.class, iter::peek); + assertThrows(NoSuchElementException.class, iter::next); + assertThrows(NoSuchElementException.class, iter::peek); } @@ -170,17 +155,12 @@ public void testDefaultBehaviorOfPeekForEmptyIteration() { } }; - try { - empty.peek(); - fail("peek() should throw NoSuchElementException at end"); - } catch (NoSuchElementException expected) { - } - - try { - empty.peek(); - fail("peek() should continue to throw NoSuchElementException at end"); - } catch (NoSuchElementException expected) { - } + /* + * We test multiple calls to peek() to make sure that one bad call doesn't interfere with its + * ability to throw the correct exception in the future. + */ + assertThrows(NoSuchElementException.class, empty::peek); + assertThrows(NoSuchElementException.class, empty::peek); } public void testSneakyThrow() throws Exception { @@ -201,21 +181,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() { @@ -229,12 +197,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() { @@ -246,11 +210,7 @@ public Integer computeNext() { throw new SomeUncheckedException(); } }; - try { - iter.hasNext(); - fail("No exception thrown"); - } catch (SomeUncheckedException expected) { - } + assertThrows(SomeUncheckedException.class, iter::hasNext); } @SuppressWarnings("DoNotCall") @@ -271,11 +231,7 @@ public Integer computeNext() { assertEquals(0, (int) iter.next()); - try { - iter.remove(); - fail("No exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, iter::remove); } public void testReentrantHasNext() { @@ -287,11 +243,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 (9 combinations of @@ -308,8 +260,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/collect/AbstractMapsTransformValuesTest.java b/guava-tests/test/com/google/common/collect/AbstractMapsTransformValuesTest.java index 67a47e67d355..218716ceb279 100644 --- a/guava-tests/test/com/google/common/collect/AbstractMapsTransformValuesTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractMapsTransformValuesTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -87,23 +89,13 @@ public void testTransformIdentityFunctionEquality() { public void testTransformPutEntryIsUnsupported() { Map map = Maps.transformValues(ImmutableMap.of("a", 1), Functions.toStringFunction()); - try { - map.put("b", "2"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.put("b", "2")); - try { - map.putAll(ImmutableMap.of("b", "2")); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.putAll(ImmutableMap.of("b", "2"))); - try { - map.entrySet().iterator().next().setValue("one"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, + () -> map.entrySet().iterator().next().setValue("one")); } public void testTransformRemoveEntry() { diff --git a/guava-tests/test/com/google/common/collect/AbstractMultimapAsMapImplementsMapTest.java b/guava-tests/test/com/google/common/collect/AbstractMultimapAsMapImplementsMapTest.java index 06466c84df61..fcd6dc381023 100644 --- a/guava-tests/test/com/google/common/collect/AbstractMultimapAsMapImplementsMapTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractMultimapAsMapImplementsMapTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.MapInterfaceTest; import java.util.Collection; @@ -81,11 +83,7 @@ public void testRemove() { assertFalse(map.containsKey(keyToRemove)); assertEquals(initialSize - 1, map.size()); } else { - try { - map.remove(keyToRemove); - fail("Expected UnsupportedOperationException."); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.remove(keyToRemove)); } assertInvariants(map); } diff --git a/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java b/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java index 9b813c4bafa6..b1f64347ee53 100644 --- a/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java @@ -16,11 +16,13 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; +import com.google.common.collect.TestExceptions.SomeUncheckedException; import com.google.common.collect.testing.IteratorTester; import java.util.Iterator; import java.util.NoSuchElementException; @@ -109,32 +111,16 @@ public Iterator iterator() { public void testEmpty() { Iterator empty = new EmptyAbstractSequentialIterator<>(); assertFalse(empty.hasNext()); - try { - empty.next(); - fail(); - } catch (NoSuchElementException expected) { - } - try { - empty.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(NoSuchElementException.class, empty::next); + assertThrows(UnsupportedOperationException.class, empty::remove); } public void testBroken() { Iterator broken = new BrokenAbstractSequentialIterator(); assertTrue(broken.hasNext()); // We can't retrieve even the known first element: - try { - broken.next(); - fail(); - } catch (MyException expected) { - } - try { - broken.next(); - fail(); - } catch (MyException expected) { - } + assertThrows(SomeUncheckedException.class, broken::next); + assertThrows(SomeUncheckedException.class, broken::next); } private static Iterator newDoubler(int first, final int last) { @@ -166,9 +152,7 @@ public BrokenAbstractSequentialIterator() { @Override protected Object computeNext(Object previous) { - throw new MyException(); + throw new SomeUncheckedException(); } } - - private static class MyException extends RuntimeException {} } diff --git a/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java b/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java index caa40a63a122..5eada001250c 100644 --- a/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractTableReadTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -159,11 +160,7 @@ public void testRow() { // This test assumes that the implementation does not support null keys. public void testRowNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); - try { - table.row(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.row(null)); } public void testColumn() { @@ -174,11 +171,7 @@ public void testColumn() { // This test assumes that the implementation does not support null keys. public void testColumnNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); - try { - table.column(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.column(null)); } public void testColumnSetPartialOverlap() { diff --git a/guava-tests/test/com/google/common/collect/AbstractTableTest.java b/guava-tests/test/com/google/common/collect/AbstractTableTest.java index 0639f2d325d0..264bb06f0a80 100644 --- a/guava-tests/test/com/google/common/collect/AbstractTableTest.java +++ b/guava-tests/test/com/google/common/collect/AbstractTableTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import java.util.Map; @@ -57,11 +58,7 @@ public void testClear() { assertEquals(0, table.size()); assertFalse(table.containsRow("foo")); } else { - try { - table.clear(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> table.clear()); } } @@ -81,25 +78,13 @@ public void testPut() { public void testPutNull() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); assertSize(3); - try { - table.put(null, 2, cellValue('d')); - fail(); - } catch (NullPointerException expected) { - } - try { - table.put("cat", null, cellValue('d')); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.put(null, 2, cellValue('d'))); + assertThrows(NullPointerException.class, () -> table.put("cat", null, cellValue('d'))); if (supportsNullValues()) { assertNull(table.put("cat", 2, null)); assertTrue(table.contains("cat", 2)); } else { - try { - table.put("cat", 2, null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.put("cat", 2, null)); } assertSize(3); } @@ -111,11 +96,7 @@ public void testPutNullReplace() { assertEquals((Character) 'b', table.put("bar", 1, nullableCellValue(null))); assertNull(table.get("bar", 1)); } else { - try { - table.put("bar", 1, nullableCellValue(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> table.put("bar", 1, nullableCellValue(null))); } } @@ -150,11 +131,7 @@ public void testRemove() { assertNull(table.remove(null, null)); assertSize(2); } else { - try { - table.remove("foo", 3); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> table.remove("foo", 3)); assertEquals((Character) 'c', table.get("foo", 3)); } } diff --git a/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java b/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java index 20920362557b..bc18b493baa4 100644 --- a/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/ArrayListMultimapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -119,11 +120,7 @@ public void testSublistConcurrentModificationException() { assertTrue(sublist.isEmpty()); multimap.put("foo", 6); - try { - sublist.isEmpty(); - fail("Expected ConcurrentModificationException"); - } catch (ConcurrentModificationException expected) { - } + assertThrows(ConcurrentModificationException.class, () -> sublist.isEmpty()); } public void testCreateFromMultimap() { @@ -146,17 +143,9 @@ public void testCreateFromSizes() { } public void testCreateFromIllegalSizes() { - try { - ArrayListMultimap.create(15, -2); - fail(); - } catch (IllegalArgumentException expected) { - } - - try { - ArrayListMultimap.create(-15, 2); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ArrayListMultimap.create(15, -2)); + + assertThrows(IllegalArgumentException.class, () -> ArrayListMultimap.create(-15, 2)); } public void testCreateFromHashMultimap() { diff --git a/guava-tests/test/com/google/common/collect/ArrayTableTest.java b/guava-tests/test/com/google/common/collect/ArrayTableTest.java index f97a4393da7f..ca57d8f8a577 100644 --- a/guava-tests/test/com/google/common/collect/ArrayTableTest.java +++ b/guava-tests/test/com/google/common/collect/ArrayTableTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -187,35 +188,27 @@ public void testToStringSize1() { } public void testCreateDuplicateRows() { - try { - ArrayTable.create(asList("foo", "bar", "foo"), asList(1, 2, 3)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ArrayTable.create(asList("foo", "bar", "foo"), asList(1, 2, 3))); } public void testCreateDuplicateColumns() { - try { - ArrayTable.create(asList("foo", "bar"), asList(1, 2, 3, 2)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ArrayTable.create(asList("foo", "bar"), asList(1, 2, 3, 2))); } public void testCreateEmptyRows() { - try { - ArrayTable.create(Arrays.asList(), asList(1, 2, 3)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ArrayTable.create(Arrays.asList(), asList(1, 2, 3))); } public void testCreateEmptyColumns() { - try { - ArrayTable.create(asList("foo", "bar"), Arrays.asList()); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ArrayTable.create(asList("foo", "bar"), Arrays.asList())); } public void testCreateEmptyRowsXColumns() { @@ -227,11 +220,7 @@ public void testCreateEmptyRowsXColumns() { assertThat(table.rowKeyList()).isEmpty(); assertThat(table.columnKeySet()).isEmpty(); assertThat(table.rowKeySet()).isEmpty(); - try { - table.at(0, 0); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> table.at(0, 0)); } @GwtIncompatible // toArray @@ -361,26 +350,10 @@ public void testAt() { assertEquals((Character) 'b', table.at(1, 0)); assertEquals((Character) 'c', table.at(0, 2)); assertNull(table.at(1, 2)); - try { - table.at(1, 3); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.at(1, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.at(3, 2); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.at(-1, 2); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> table.at(1, 3)); + assertThrows(IndexOutOfBoundsException.class, () -> table.at(1, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> table.at(3, 2)); + assertThrows(IndexOutOfBoundsException.class, () -> table.at(-1, 2)); } public void testSet() { @@ -392,26 +365,10 @@ public void testSet() { assertEquals((Character) 'e', table.get("cat", 1)); assertEquals((Character) 'a', table.set(0, 0, null)); assertNull(table.get("foo", 1)); - try { - table.set(1, 3, 'z'); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.set(1, -1, 'z'); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.set(3, 2, 'z'); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - table.set(-1, 2, 'z'); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> table.set(1, 3, 'z')); + assertThrows(IndexOutOfBoundsException.class, () -> table.set(1, -1, 'z')); + assertThrows(IndexOutOfBoundsException.class, () -> table.set(3, 2, 'z')); + assertThrows(IndexOutOfBoundsException.class, () -> table.set(-1, 2, 'z')); assertFalse(table.containsValue('z')); } @@ -427,18 +384,11 @@ public void testEraseAll() { public void testPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); - try { - table.put("dog", 1, 'd'); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Row dog not in [foo, bar, cat]"); - } - try { - table.put("foo", 4, 'd'); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Column 4 not in [1, 2, 3]"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> table.put("dog", 1, 'd')); + assertThat(expected).hasMessageThat().isEqualTo("Row dog not in [foo, bar, cat]"); + expected = assertThrows(IllegalArgumentException.class, () -> table.put("foo", 4, 'd')); + assertThat(expected).hasMessageThat().isEqualTo("Column 4 not in [1, 2, 3]"); assertFalse(table.containsValue('d')); } @@ -483,44 +433,30 @@ public void testRowMissing() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map row = table.row("dog"); assertTrue(row.isEmpty()); - try { - row.put(1, 'd'); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> row.put(1, 'd')); } public void testColumnMissing() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map column = table.column(4); assertTrue(column.isEmpty()); - try { - column.put("foo", 'd'); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> column.put("foo", 'd')); } public void testRowPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map map = table.row("foo"); - try { - map.put(4, 'd'); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Column 4 not in [1, 2, 3]"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> map.put(4, 'd')); + assertThat(expected).hasMessageThat().isEqualTo("Column 4 not in [1, 2, 3]"); } public void testColumnPutIllegal() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map map = table.column(3); - try { - map.put("dog", 'd'); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("Row dog not in [foo, bar, cat]"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> map.put("dog", 'd')); + assertThat(expected).hasMessageThat().isEqualTo("Row dog not in [foo, bar, cat]"); } @J2ktIncompatible diff --git a/guava-tests/test/com/google/common/collect/ContiguousSetTest.java b/guava-tests/test/com/google/common/collect/ContiguousSetTest.java index 63edca44b7b5..abca6e75e499 100644 --- a/guava-tests/test/com/google/common/collect/ContiguousSetTest.java +++ b/guava-tests/test/com/google/common/collect/ContiguousSetTest.java @@ -19,6 +19,7 @@ import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.DiscreteDomain.integers; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.NON_STANDARD_TOSTRING; @@ -79,29 +80,13 @@ public Integer maxValue() { }; public void testInvalidIntRange() { - try { - ContiguousSet.closed(2, 1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - ContiguousSet.closedOpen(2, 1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ContiguousSet.closed(2, 1)); + assertThrows(IllegalArgumentException.class, () -> ContiguousSet.closedOpen(2, 1)); } public void testInvalidLongRange() { - try { - ContiguousSet.closed(2L, 1L); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - ContiguousSet.closedOpen(2L, 1L); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ContiguousSet.closed(2L, 1L)); + assertThrows(IllegalArgumentException.class, () -> ContiguousSet.closedOpen(2L, 1L)); } public void testEquals() { @@ -178,20 +163,16 @@ public long distance(Integer start, Integer end) { public void testCreate_noMin() { Range range = Range.lessThan(0); - try { - ContiguousSet.create(range, UNBOUNDED_THROWING_DOMAIN); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ContiguousSet.create(range, UNBOUNDED_THROWING_DOMAIN)); } public void testCreate_noMax() { Range range = Range.greaterThan(0); - try { - ContiguousSet.create(range, UNBOUNDED_THROWING_DOMAIN); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> ContiguousSet.create(range, UNBOUNDED_THROWING_DOMAIN)); } public void testCreate_empty() { @@ -257,11 +238,7 @@ public void testSubSet() { public void testSubSet_outOfOrder() { ImmutableSortedSet set = ContiguousSet.create(Range.closed(1, 3), integers()); - try { - set.subSet(3, 2); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> set.subSet(3, 2)); } public void testSubSet_tooLarge() { diff --git a/guava-tests/test/com/google/common/collect/EnumBiMapTest.java b/guava-tests/test/com/google/common/collect/EnumBiMapTest.java index 93c45a340b73..88e80b3f96f2 100644 --- a/guava-tests/test/com/google/common/collect/EnumBiMapTest.java +++ b/guava-tests/test/com/google/common/collect/EnumBiMapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.orderEntriesByKey; import static com.google.common.truth.Truth.assertThat; @@ -152,16 +153,12 @@ public void testCreateFromMap() { assertEquals(Currency.DOLLAR, bimap.inverse().get(Country.CANADA)); /* Map must have at least one entry if not an EnumBiMap. */ - try { - EnumBiMap.create(Collections.emptyMap()); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } - try { - EnumBiMap.create(EnumHashBiMap.create(Currency.class)); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> EnumBiMap.create(Collections.emptyMap())); + assertThrows( + IllegalArgumentException.class, + () -> EnumBiMap.create(EnumHashBiMap.create(Currency.class))); /* Map can be empty if it's an EnumBiMap. */ Map emptyBimap = EnumBiMap.create(Currency.class, Country.class); diff --git a/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java b/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java index 02ae0b616284..352b069d322a 100644 --- a/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java +++ b/guava-tests/test/com/google/common/collect/EnumHashBiMapTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -145,11 +147,9 @@ public void testCreateFromMap() { assertEquals(Currency.DOLLAR, bimap.inverse().get("dollar")); /* Map must have at least one entry if not an EnumHashBiMap. */ - try { - EnumHashBiMap.create(Collections.emptyMap()); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> EnumHashBiMap.create(Collections.emptyMap())); /* Map can be empty if it's an EnumHashBiMap. */ Map emptyBimap = EnumHashBiMap.create(Currency.class); diff --git a/guava-tests/test/com/google/common/collect/EnumMultisetTest.java b/guava-tests/test/com/google/common/collect/EnumMultisetTest.java index f40547793be8..4a3fc9d07e4e 100644 --- a/guava-tests/test/com/google/common/collect/EnumMultisetTest.java +++ b/guava-tests/test/com/google/common/collect/EnumMultisetTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; @@ -30,6 +31,7 @@ import com.google.common.testing.ClassSanityTester; import com.google.common.testing.NullPointerTester; import com.google.common.testing.SerializableTester; +import com.google.errorprone.annotations.Keep; import java.util.Collection; import java.util.EnumSet; import java.util.Set; @@ -108,11 +110,7 @@ public void testCollectionCreate() { public void testIllegalCreate() { Collection empty = EnumSet.noneOf(Color.class); - try { - EnumMultiset.create(empty); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> EnumMultiset.create(empty)); } public void testCreateEmptyWithClass() { @@ -121,11 +119,8 @@ public void testCreateEmptyWithClass() { } public void testCreateEmptyWithoutClassFails() { - try { - EnumMultiset.create(ImmutableList.of()); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> EnumMultiset.create(ImmutableList.of())); } public void testToString() { @@ -157,6 +152,7 @@ public void testEntrySet() { // create(Enum1.class) is equal to create(Enum2.class) but testEquals() expects otherwise. // For the same reason, we need to skip create(Iterable, Class). private static class EnumMultisetFactory { + @Keep // used reflectively by testEquals public static > EnumMultiset create(Iterable elements) { return EnumMultiset.create(elements); } diff --git a/guava-tests/test/com/google/common/collect/EvictingQueueTest.java b/guava-tests/test/com/google/common/collect/EvictingQueueTest.java index 0e23035d86a6..7ba7923aed5c 100644 --- a/guava-tests/test/com/google/common/collect/EvictingQueueTest.java +++ b/guava-tests/test/com/google/common/collect/EvictingQueueTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -36,11 +38,7 @@ public class EvictingQueueTest extends TestCase { public void testCreateWithNegativeSize() throws Exception { - try { - EvictingQueue.create(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> EvictingQueue.create(-1)); } public void testCreateWithZeroSize() throws Exception { @@ -56,19 +54,11 @@ public void testCreateWithZeroSize() throws Exception { assertFalse(queue.remove("hi")); assertEquals(0, queue.size()); - try { - queue.element(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> queue.element()); assertNull(queue.peek()); assertNull(queue.poll()); - try { - queue.remove(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> queue.remove()); } public void testRemainingCapacity_maxSize0() { diff --git a/guava-tests/test/com/google/common/collect/FluentIterableTest.java b/guava-tests/test/com/google/common/collect/FluentIterableTest.java index 8f1fc487d0fa..bbc850ef3b3e 100644 --- a/guava-tests/test/com/google/common/collect/FluentIterableTest.java +++ b/guava-tests/test/com/google/common/collect/FluentIterableTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -63,11 +64,9 @@ public void testFromArrayAndAppend() { public void testFromArrayAndIteratorRemove() { FluentIterable units = FluentIterable.from(TimeUnit.values()); - try { - Iterables.removeIf(units, Predicates.equalTo(TimeUnit.SECONDS)); - fail("Expected an UnsupportedOperationException to be thrown but it wasn't."); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, + () -> Iterables.removeIf(units, Predicates.equalTo(TimeUnit.SECONDS))); } public void testFrom() { @@ -131,11 +130,7 @@ public void testConcatNullPointerException() { List list1 = newArrayList(1); List list2 = newArrayList(4); - try { - FluentIterable.concat(list1, null, list2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> FluentIterable.concat(list1, null, list2)); } public void testConcatPeformingFiniteCycle() { @@ -326,12 +321,12 @@ public void testAppend_emptyList() { } public void testAppend_nullPointerException() { - try { - FluentIterable unused = - FluentIterable.from(asList(1, 2)).append((List) null); - fail("Appending null iterable should throw NPE."); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> { + FluentIterable unused = + FluentIterable.from(asList(1, 2)).append((List) null); + }); } /* @@ -423,11 +418,7 @@ public void testTransformWith_poorlyBehavedTransform() { Iterator resultIterator = iterable.iterator(); resultIterator.next(); - try { - resultIterator.next(); - fail("Transforming null to int should throw NumberFormatException"); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> resultIterator.next()); } private static final class StringValueOfFunction implements Function { @@ -482,11 +473,7 @@ public void testFirst_list() { public void testFirst_null() { List list = Lists.newArrayList(null, "a", "b"); - try { - FluentIterable.from(list).first(); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> FluentIterable.from(list).first()); } public void testFirst_emptyList() { @@ -521,11 +508,7 @@ public void testLast_list() { public void testLast_null() { List list = Lists.newArrayList("a", "b", null); - try { - FluentIterable.from(list).last(); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> FluentIterable.from(list).last()); } public void testLast_emptyList() { @@ -661,11 +644,8 @@ public void testSkip_structurallyModifiedSkipAllList() throws Exception { } public void testSkip_illegalArgument() { - try { - FluentIterable.from(asList("a", "b", "c")).skip(-1); - fail("Skipping negative number of elements should throw IllegalArgumentException."); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> FluentIterable.from(asList("a", "b", "c")).skip(-1)); } public void testLimit() { @@ -678,12 +658,12 @@ public void testLimit() { } public void testLimit_illegalArgument() { - try { - FluentIterable unused = - FluentIterable.from(Lists.newArrayList("a", "b", "c")).limit(-1); - fail("Passing negative number to limit(...) method should throw IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> { + FluentIterable unused = + FluentIterable.from(Lists.newArrayList("a", "b", "c")).limit(-1); + }); } public void testIsEmpty() { @@ -751,19 +731,12 @@ public void testToMap() { } public void testToMap_nullKey() { - try { - fluent(1, null, 2).toMap(Functions.constant("foo")); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> fluent(1, null, 2).toMap(Functions.constant("foo"))); } public void testToMap_nullValue() { - try { - fluent(1, 2, 3).toMap(Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> fluent(1, 2, 3).toMap(Functions.constant(null))); } public void testIndex() { @@ -786,21 +759,21 @@ public Integer apply(String input) { } public void testIndex_nullKey() { - try { - ImmutableListMultimap unused = - fluent(1, 2, 3).index(Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> { + ImmutableListMultimap unused = + fluent(1, 2, 3).index(Functions.constant(null)); + }); } public void testIndex_nullValue() { - try { - ImmutableListMultimap unused = - fluent(1, null, 2).index(Functions.constant("foo")); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> { + ImmutableListMultimap unused = + fluent(1, null, 2).index(Functions.constant("foo")); + }); } public void testUniqueIndex() { @@ -818,43 +791,40 @@ public Integer apply(String input) { } public void testUniqueIndex_duplicateKey() { - try { - ImmutableMap unused = - FluentIterable.from(asList("one", "two", "three", "four")) - .uniqueIndex( - new Function() { - @Override - public Integer apply(String input) { - return input.length(); - } - }); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> { + ImmutableMap unused = + FluentIterable.from(asList("one", "two", "three", "four")) + .uniqueIndex( + new Function() { + @Override + public Integer apply(String input) { + return input.length(); + } + }); + }); } public void testUniqueIndex_nullKey() { - try { - fluent(1, 2, 3).uniqueIndex(Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> fluent(1, 2, 3).uniqueIndex(Functions.constant(null))); } public void testUniqueIndex_nullValue() { - try { - ImmutableMap unused = - fluent(1, null, 2) - .uniqueIndex( - new Function() { - @Override - public Object apply(@Nullable Integer input) { - return String.valueOf(input); - } - }); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> { + ImmutableMap unused = + fluent(1, null, 2) + .uniqueIndex( + new Function() { + @Override + public Object apply(@Nullable Integer input) { + return String.valueOf(input); + } + }); + }); } public void testCopyInto_list() { @@ -903,17 +873,13 @@ public void testGet() { } public void testGet_outOfBounds() { - try { - FluentIterable.from(Lists.newArrayList("a", "b", "c")).get(-1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows( + IndexOutOfBoundsException.class, + () -> FluentIterable.from(Lists.newArrayList("a", "b", "c")).get(-1)); - try { - FluentIterable.from(Lists.newArrayList("a", "b", "c")).get(3); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows( + IndexOutOfBoundsException.class, + () -> FluentIterable.from(Lists.newArrayList("a", "b", "c")).get(3)); } /* diff --git a/guava-tests/test/com/google/common/collect/GeneralRangeTest.java b/guava-tests/test/com/google/common/collect/GeneralRangeTest.java index c50f1f5c46d1..cca29faecf08 100644 --- a/guava-tests/test/com/google/common/collect/GeneralRangeTest.java +++ b/guava-tests/test/com/google/common/collect/GeneralRangeTest.java @@ -16,6 +16,7 @@ import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -43,22 +44,18 @@ public class GeneralRangeTest extends TestCase { public void testCreateEmptyRangeFails() { for (BoundType lboundType : BoundType.values()) { for (BoundType uboundType : BoundType.values()) { - try { - GeneralRange.range(ORDERING, 4, lboundType, 2, uboundType); - fail("Expected IAE"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> GeneralRange.range(ORDERING, 4, lboundType, 2, uboundType)); } } } public void testCreateEmptyRangeOpenOpenFails() { for (Integer i : IN_ORDER_VALUES) { - try { - GeneralRange.<@Nullable Integer>range(ORDERING, i, OPEN, i, OPEN); - fail("Expected IAE"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> GeneralRange.<@Nullable Integer>range(ORDERING, i, OPEN, i, OPEN)); } } diff --git a/guava-tests/test/com/google/common/collect/HashBasedTableTest.java b/guava-tests/test/com/google/common/collect/HashBasedTableTest.java index 15ca3482d2e6..d5ed5751ad52 100644 --- a/guava-tests/test/com/google/common/collect/HashBasedTableTest.java +++ b/guava-tests/test/com/google/common/collect/HashBasedTableTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -73,17 +74,9 @@ public void testCreateWithValidSizes() { } public void testCreateWithInvalidSizes() { - try { - HashBasedTable.create(100, -5); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> HashBasedTable.create(100, -5)); - try { - HashBasedTable.create(-5, 20); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> HashBasedTable.create(-5, 20)); } public void testCreateCopy() { diff --git a/guava-tests/test/com/google/common/collect/HashMultimapTest.java b/guava-tests/test/com/google/common/collect/HashMultimapTest.java index 6943656b3938..0fa8ac353c9a 100644 --- a/guava-tests/test/com/google/common/collect/HashMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/HashMultimapTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; @@ -102,17 +104,9 @@ public void testCreateFromSizes() { } public void testCreateFromIllegalSizes() { - try { - HashMultimap.create(-20, 15); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> HashMultimap.create(-20, 15)); - try { - HashMultimap.create(20, -15); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> HashMultimap.create(20, -15)); } public void testEmptyMultimapsEqual() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java index 0b2d1296d667..ac8a88fd7ff9 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.truth.Truth.assertThat; @@ -197,11 +198,8 @@ public void testBuilder_orderEntriesByValueAfterExactSizeBuild() { public void testBuilder_orderEntriesByValue_usedTwiceFails() { ImmutableBiMap.Builder builder = new Builder().orderEntriesByValue(Ordering.natural()); - try { - builder.orderEntriesByValue(Ordering.natural()); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows( + IllegalStateException.class, () -> builder.orderEntriesByValue(Ordering.natural())); } public void testBuilderPutAllWithEmptyMap() { @@ -238,38 +236,26 @@ public void testBuilderReuse() { public void testBuilderPutNullKey() { Builder builder = new Builder<>(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); } public void testBuilderPutNullValue() { Builder builder = new Builder<>(); - try { - builder.put("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("one", null)); } public void testBuilderPutNullKeyViaPutAll() { Builder builder = new Builder<>(); - try { - builder.putAll(Collections.singletonMap(null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap(null, 1))); } public void testBuilderPutNullValueViaPutAll() { Builder builder = new Builder<>(); - try { - builder.putAll(Collections.singletonMap("one", null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap("one", null))); } @SuppressWarnings("AlwaysThrows") @@ -279,12 +265,9 @@ public void testPuttingTheSameKeyTwiceThrowsOnBuild() { .put("one", 1) .put("one", 1); // throwing on this line would be even better - try { - builder.build(); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("one"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> builder.build()); + assertThat(expected.getMessage()).contains("one"); } public void testOf() { @@ -479,41 +462,22 @@ public void testOf() { } public void testOfNullKey() { - try { - ImmutableBiMap.of(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableBiMap.of(null, 1)); - try { - ImmutableBiMap.of("one", 1, null, 2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableBiMap.of("one", 1, null, 2)); } public void testOfNullValue() { - try { - ImmutableBiMap.of("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableBiMap.of("one", null)); - try { - ImmutableBiMap.of("one", 1, "two", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableBiMap.of("one", 1, "two", null)); } - @SuppressWarnings("AlwaysThrows") + @SuppressWarnings({"AlwaysThrows", "DistinctVarargsChecker"}) public void testOfWithDuplicateKey() { - try { - ImmutableBiMap.of("one", 1, "one", 1); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("one"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> ImmutableBiMap.of("one", 1, "one", 1)); + assertThat(expected.getMessage()).contains("one"); } public void testOfEntries() { @@ -522,18 +486,14 @@ public void testOfEntries() { public void testOfEntriesNull() { Entry<@Nullable Integer, Integer> nullKey = entry(null, 23); - try { - ImmutableBiMap.ofEntries((Entry) nullKey); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableBiMap.ofEntries((Entry) nullKey)); Entry nullValue = ImmutableBiMapTest.<@Nullable Integer>entry(23, null); - try { - ImmutableBiMap.ofEntries((Entry) nullValue); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableBiMap.ofEntries((Entry) nullValue)); } private static Entry entry(T key, T value) { @@ -604,13 +564,9 @@ public void testDuplicateValues() { .put("dos", 2) .buildOrThrow(); - try { - ImmutableBiMap.copyOf(map); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).containsMatch("1|2"); - // We don't specify which of the two dups should be reported. - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> ImmutableBiMap.copyOf(map)); + assertThat(expected.getMessage()).containsMatch("1|2"); } public void testToImmutableBiMap() { @@ -631,11 +587,9 @@ public void testToImmutableBiMap() { public void testToImmutableBiMap_exceptionOnDuplicateKey() { Collector, ?, ImmutableBiMap> collector = ImmutableBiMap.toImmutableBiMap(Entry::getKey, Entry::getValue); - try { - Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector)); } // BiMap-specific tests @@ -643,11 +597,7 @@ public void testToImmutableBiMap_exceptionOnDuplicateKey() { @SuppressWarnings("DoNotCall") public void testForcePut() { BiMap bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2)); - try { - bimap.forcePut("three", 3); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> bimap.forcePut("three", 3)); } public void testKeySet() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableEnumMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableEnumMapTest.java index f0f77451686e..32543c74bf26 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableEnumMapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableEnumMapTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkState; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; @@ -124,11 +125,9 @@ public void testToImmutableEnumMap() { public void testToImmutableMap_exceptionOnDuplicateKey() { Collector, ?, ImmutableMap> collector = Maps.toImmutableEnumMap(Entry::getKey, Entry::getValue); - try { - Stream.of(mapEntry(AnEnum.A, 1), mapEntry(AnEnum.A, 11)).collect(collector); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Stream.of(mapEntry(AnEnum.A, 1), mapEntry(AnEnum.A, 11)).collect(collector)); } public void testToImmutableMapMerging() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java b/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java index 9735f752edf0..6607e6d86335 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableListMultimapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; @@ -93,11 +94,8 @@ public static Test suite() { } public void testBuilderWithExpectedKeysNegative() { - try { - ImmutableListMultimap.builderWithExpectedKeys(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> ImmutableListMultimap.builderWithExpectedKeys(-1)); } public void testBuilderWithExpectedKeysZero() { @@ -116,11 +114,7 @@ public void testBuilderWithExpectedKeysPositive() { public void testBuilderWithExpectedValuesPerKeyNegative() { ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); - try { - builder.expectedValuesPerKey(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.expectedValuesPerKey(-1)); } public void testBuilderWithExpectedValuesPerKeyZero() { @@ -145,16 +139,10 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } private static class StringHolder { @@ -271,52 +259,23 @@ public void testBuilderPutNullKey() { Multimap<@Nullable String, Integer> toPut = LinkedListMultimap.create(); toPut.put(null, 1); ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll(null, Arrays.asList(1, 2, 3)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll(null, 1, 2, 3); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll((Multimap) toPut); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); + assertThrows(NullPointerException.class, () -> builder.putAll(null, Arrays.asList(1, 2, 3))); + assertThrows(NullPointerException.class, () -> builder.putAll(null, 1, 2, 3)); + assertThrows( + NullPointerException.class, () -> builder.putAll((Multimap) toPut)); } public void testBuilderPutNullValue() { Multimap toPut = LinkedListMultimap.create(); toPut.put("foo", null); ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder(); - try { - builder.put("foo", null); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll("foo", Arrays.asList(1, null, 3)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll("foo", 1, null, 3); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll((Multimap) toPut); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("foo", null)); + assertThrows( + NullPointerException.class, () -> builder.putAll("foo", Arrays.asList(1, null, 3))); + assertThrows(NullPointerException.class, () -> builder.putAll("foo", 1, null, 3)); + assertThrows( + NullPointerException.class, () -> builder.putAll((Multimap) toPut)); } public void testBuilderOrderKeysBy() { @@ -426,21 +385,17 @@ public void testCopyOfImmutableListMultimap() { public void testCopyOfNullKey() { ArrayListMultimap<@Nullable String, Integer> input = ArrayListMultimap.create(); input.put(null, 1); - try { - ImmutableListMultimap.copyOf((ArrayListMultimap) input); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableListMultimap.copyOf((ArrayListMultimap) input)); } public void testCopyOfNullValue() { ArrayListMultimap input = ArrayListMultimap.create(); input.putAll("foo", Arrays.<@Nullable Integer>asList(1, null, 3)); - try { - ImmutableListMultimap.copyOf((ArrayListMultimap) input); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableListMultimap.copyOf((ArrayListMultimap) input)); } public void testToImmutableListMultimap() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableListTest.java b/guava-tests/test/com/google/common/collect/ImmutableListTest.java index f3936a34fe0a..924b4fdfab81 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableListTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableListTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; import static com.google.common.truth.Truth.assertThat; @@ -196,19 +197,11 @@ public void testCreation_fourteenElements() { } public void testCreation_singletonNull() { - try { - ImmutableList.of((String) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.of((String) null)); } public void testCreation_withNull() { - try { - ImmutableList.of("a", null, "b"); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.of("a", null, "b")); } public void testCreation_generic() { @@ -236,20 +229,12 @@ public void testCopyOf_arrayOfOneElement() { } public void testCopyOf_nullArray() { - try { - ImmutableList.copyOf((String[]) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.copyOf((String[]) null)); } public void testCopyOf_arrayContainingOnlyNull() { @Nullable String[] array = new @Nullable String[] {null}; - try { - ImmutableList.copyOf((String[]) array); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.copyOf((String[]) array)); } public void testCopyOf_collection_empty() { @@ -277,11 +262,7 @@ public void testCopyOf_collection_general() { public void testCopyOf_collectionContainingNull() { Collection<@Nullable String> c = MinimalCollection.of("a", null, "b"); - try { - ImmutableList.copyOf((Collection) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.copyOf((Collection) c)); } public void testCopyOf_iterator_empty() { @@ -305,19 +286,12 @@ public void testCopyOf_iterator_general() { public void testCopyOf_iteratorContainingNull() { Iterator<@Nullable String> iterator = Arrays.<@Nullable String>asList("a", null, "b").iterator(); - try { - ImmutableList.copyOf((Iterator) iterator); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> ImmutableList.copyOf((Iterator) iterator)); } public void testCopyOf_iteratorNull() { - try { - ImmutableList.copyOf((Iterator) null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableList.copyOf((Iterator) null)); } public void testCopyOf_concurrentlyMutating() { @@ -373,11 +347,7 @@ public void testCopyOf_shortcut_immutableList() { public void testBuilderAddArrayHandlesNulls() { @Nullable String[] elements = new @Nullable String[] {"a", null, "b"}; ImmutableList.Builder builder = ImmutableList.builder(); - try { - builder.add((String[]) elements); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add((String[]) elements)); ImmutableList result = builder.build(); /* @@ -394,11 +364,7 @@ public void testBuilderAddArrayHandlesNulls() { public void testBuilderAddCollectionHandlesNulls() { List<@Nullable String> elements = Arrays.asList("a", null, "b"); ImmutableList.Builder builder = ImmutableList.builder(); - try { - builder.addAll((List) elements); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.addAll((List) elements)); ImmutableList result = builder.build(); assertEquals(ImmutableList.of("a"), result); assertEquals(1, result.size()); @@ -424,11 +390,8 @@ public void testSortedCopyOf_natural_singleton() { public void testSortedCopyOf_natural_containsNull() { Collection<@Nullable Integer> c = MinimalCollection.of(1, 3, null, 2); - try { - ImmutableList.sortedCopyOf((Collection) c); - fail("Expected NPE"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> ImmutableList.sortedCopyOf((Collection) c)); } public void testSortedCopyOf() { @@ -451,11 +414,9 @@ public void testSortedCopyOf_singleton() { public void testSortedCopyOf_containsNull() { Collection<@Nullable String> c = MinimalCollection.of("a", "b", "A", null, "c"); - try { - ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, (Collection) c); - fail("Expected NPE"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableList.sortedCopyOf(String.CASE_INSENSITIVE_ORDER, (Collection) c)); } public void testToImmutableList() { @@ -591,61 +552,43 @@ public void testComplexBuilder() { public void testBuilderAddHandlesNullsCorrectly() { ImmutableList.Builder builder = ImmutableList.builder(); - try { - builder.add((String) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add((String) null)); - try { - builder.add((String[]) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add((String[]) null)); - try { - builder.add("a", null, "b"); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add("a", null, "b")); } public void testBuilderAddAllHandlesNullsCorrectly() { + { ImmutableList.Builder builder = ImmutableList.builder(); - try { - builder.addAll((Iterable) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((Iterable) null)); } - try { - builder.addAll((Iterator) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + { + ImmutableList.Builder builder = ImmutableList.builder(); + assertThrows(NullPointerException.class, () -> builder.addAll((Iterator) null)); } - builder = ImmutableList.builder(); + { + ImmutableList.Builder builder = ImmutableList.builder(); List<@Nullable String> listWithNulls = asList("a", null, "b"); - try { - builder.addAll((List) listWithNulls); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((List) listWithNulls)); } - builder = ImmutableList.builder(); + { + ImmutableList.Builder builder = ImmutableList.builder(); Iterator<@Nullable String> iteratorWithNulls = Arrays.<@Nullable String>asList("a", null, "b").iterator(); - try { - builder.addAll((Iterator) iteratorWithNulls); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows( + NullPointerException.class, () -> builder.addAll((Iterator) iteratorWithNulls)); } + { + ImmutableList.Builder builder = ImmutableList.builder(); Iterable<@Nullable String> iterableWithNulls = MinimalIterable.of("a", null, "b"); - try { - builder.addAll((Iterable) iterableWithNulls); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows( + NullPointerException.class, () -> builder.addAll((Iterable) iterableWithNulls)); } } @@ -662,11 +605,10 @@ public void testAddOverflowCollection() { for (int i = 0; i < 100; i++) { builder.add("a"); } - try { - builder.addAll(Collections.nCopies(Integer.MAX_VALUE - 50, "a")); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("cannot store more than MAX_VALUE elements"); - } + IllegalArgumentException expected = + assertThrows( + IllegalArgumentException.class, + () -> builder.addAll(Collections.nCopies(Integer.MAX_VALUE - 50, "a"))); + assertThat(expected).hasMessageThat().contains("cannot store more than MAX_VALUE elements"); } } diff --git a/guava-tests/test/com/google/common/collect/ImmutableMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableMapTest.java index 9936a868c83d..4af429746547 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableMapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableMapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.truth.Truth.assertThat; @@ -261,11 +262,8 @@ public void testBuilder_orderEntriesByValueAfterExactSizeBuild() { public void testBuilder_orderEntriesByValue_usedTwiceFails() { ImmutableMap.Builder builder = new Builder().orderEntriesByValue(Ordering.natural()); - try { - builder.orderEntriesByValue(Ordering.natural()); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows( + IllegalStateException.class, () -> builder.orderEntriesByValue(Ordering.natural())); } @GwtIncompatible // we haven't implemented this @@ -282,11 +280,7 @@ public void testBuilder_orderEntriesByValue_keepingLast() { .put("two", 2); assertMapEquals( builder.buildKeepingLast(), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); - try { - builder.buildOrThrow(); - fail("Expected exception from duplicate keys"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.buildOrThrow()); } @GwtIncompatible // we haven't implemented this @@ -307,11 +301,7 @@ public void testBuilder_orderEntriesByValue_keepingLast_builderSizeFieldPreserve .put("one", 1) .put("one", 1); assertMapEquals(builder.buildKeepingLast(), "one", 1); - try { - builder.buildOrThrow(); - fail("Expected exception from duplicate keys"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.buildOrThrow()); } public void testBuilder_withImmutableEntry() { @@ -322,16 +312,10 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } private static class StringHolder { @@ -393,22 +377,15 @@ public void testBuilderReuse() { public void testBuilderPutNullKeyFailsAtomically() { Builder builder = new Builder<>(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); builder.put("foo", 2); assertMapEquals(builder.buildOrThrow(), "foo", 2); } public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); builder.put("foo", 2); assertMapEquals(builder.buildOrThrow(), "foo", 2); } @@ -436,49 +413,34 @@ public V getValue() { public void testBuilderPutMutableEntryWithNullKeyFailsAtomically() { Builder builder = new Builder<>(); - try { - builder.put(new SimpleEntry(null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(new SimpleEntry(null, 1))); builder.put("foo", 2); assertMapEquals(builder.buildOrThrow(), "foo", 2); } public void testBuilderPutNullKey() { Builder builder = new Builder<>(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); } public void testBuilderPutNullValue() { Builder builder = new Builder<>(); - try { - builder.put("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("one", null)); } public void testBuilderPutNullKeyViaPutAll() { Builder builder = new Builder<>(); - try { - builder.putAll(Collections.singletonMap(null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap(null, 1))); } public void testBuilderPutNullValueViaPutAll() { Builder builder = new Builder<>(); - try { - builder.putAll(Collections.singletonMap("one", null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap("one", null))); } public void testPuttingTheSameKeyTwiceThrowsOnBuild() { @@ -487,11 +449,7 @@ public void testPuttingTheSameKeyTwiceThrowsOnBuild() { .put("one", 1) .put("one", 1); // throwing on this line might be better but it's too late to change - try { - builder.buildOrThrow(); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.buildOrThrow()); } public void testBuildKeepingLast_allowsOverwrite() { @@ -616,19 +574,16 @@ public void testBuilder_keepingLast_thenOrThrow() { .put("two", 2); assertMapEquals( builder.buildKeepingLast(), "three", 3, "one", 1, "five", 5, "four", 4, "two", 2); - try { - builder.buildOrThrow(); - fail("Expected exception from duplicate keys"); - } catch (IllegalArgumentException expected) { - // We don't really care which values the exception message contains, but they should be - // different from each other. If buildKeepingLast() collapsed duplicates, that might end up - // not being true. - Pattern pattern = Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)"); - assertThat(expected).hasMessageThat().matches(pattern); + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> builder.buildOrThrow()); + // We don't really care which values the exception message contains, but they should be + // different from each other. If buildKeepingLast() collapsed duplicates, that might end up not + // being true. + Pattern pattern = Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)"); + assertThat(expected).hasMessageThat().matches(pattern); Matcher matcher = pattern.matcher(expected.getMessage()); assertThat(matcher.matches()).isTrue(); assertThat(matcher.group(1)).isNotEqualTo(matcher.group(2)); - } } public void testOf() { @@ -791,39 +746,19 @@ public void testOf() { } public void testOfNullKey() { - try { - ImmutableMap.of(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMap.of(null, 1)); - try { - ImmutableMap.of("one", 1, null, 2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMap.of("one", 1, null, 2)); } public void testOfNullValue() { - try { - ImmutableMap.of("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMap.of("one", null)); - try { - ImmutableMap.of("one", 1, "two", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMap.of("one", 1, "two", null)); } public void testOfWithDuplicateKey() { - try { - ImmutableMap.of("one", 1, "one", 1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ImmutableMap.of("one", 1, "one", 1)); } public void testCopyOfEmptyMap() { @@ -866,11 +801,9 @@ public void testToImmutableMap() { public void testToImmutableMap_exceptionOnDuplicateKey() { Collector, ?, ImmutableMap> collector = ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue); - try { - Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector)); } public void testToImmutableMapMerging() { @@ -1179,17 +1112,13 @@ public void testEquals() { public void testOfEntriesNull() { Entry<@Nullable Integer, @Nullable Integer> nullKey = entry(null, 23); - try { - ImmutableMap.ofEntries((Entry) nullKey); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableMap.ofEntries((Entry) nullKey)); Entry<@Nullable Integer, @Nullable Integer> nullValue = entry(23, null); - try { - ImmutableMap.ofEntries((Entry) nullValue); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableMap.ofEntries((Entry) nullValue)); } private static Map map(T... keysAndValues) { diff --git a/guava-tests/test/com/google/common/collect/ImmutableMultimapTest.java b/guava-tests/test/com/google/common/collect/ImmutableMultimapTest.java index 12dcf31b8ded..9dddb7b35e49 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableMultimapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -50,24 +51,15 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } public void testBuilderWithExpectedKeysNegative() { - try { - ImmutableMultimap.builderWithExpectedKeys(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> ImmutableMultimap.builderWithExpectedKeys(-1)); } public void testBuilderWithExpectedKeysZero() { @@ -85,11 +77,8 @@ public void testBuilderWithExpectedKeysPositive() { } public void testBuilderWithExpectedValuesPerKeyNegative() { - try { - ImmutableMultimap.builder().expectedValuesPerKey(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> ImmutableMultimap.builder().expectedValuesPerKey(-1)); } public void testBuilderWithExpectedValuesPerKeyZero() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java b/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java index a88c45d2fc45..8cb5c6817e8b 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableMultisetTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -219,6 +220,7 @@ public void testCreation_arrayOfOneElement() { assertEquals(HashMultiset.create(asList("a")), multiset); } + @SuppressWarnings("ArrayAsKeyOfSetOrMap") public void testCreation_arrayOfArray() { String[] array = new String[] {"a"}; Multiset multiset = ImmutableMultiset.of(array); @@ -229,11 +231,7 @@ public void testCreation_arrayOfArray() { public void testCreation_arrayContainingOnlyNull() { @Nullable String[] array = new @Nullable String[] {null}; - try { - ImmutableMultiset.copyOf((String[]) array); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMultiset.copyOf((String[]) array)); } public void testCopyOf_collection_empty() { @@ -257,11 +255,8 @@ public void testCopyOf_collection_general() { public void testCopyOf_collectionContainingNull() { Collection<@Nullable String> c = MinimalCollection.of("a", null, "b"); - try { - ImmutableMultiset.copyOf((Collection) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> ImmutableMultiset.copyOf((Collection) c)); } public void testCopyOf_multiset_empty() { @@ -285,11 +280,7 @@ public void testCopyOf_multiset_general() { public void testCopyOf_multisetContainingNull() { Multiset<@Nullable String> c = HashMultiset.create(Arrays.<@Nullable String>asList("a", null, "b")); - try { - ImmutableMultiset.copyOf((Multiset) c); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableMultiset.copyOf((Multiset) c)); } public void testCopyOf_iterator_empty() { @@ -313,11 +304,8 @@ public void testCopyOf_iterator_general() { public void testCopyOf_iteratorContainingNull() { Iterator<@Nullable String> iterator = Arrays.<@Nullable String>asList("a", null, "b").iterator(); - try { - ImmutableMultiset.copyOf((Iterator) iterator); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> ImmutableMultiset.copyOf((Iterator) iterator)); } public void testToImmutableMultiset() { @@ -515,73 +503,48 @@ public void testBuilderSetCount() { public void testBuilderAddHandlesNullsCorrectly() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.add((String) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.add((String) null)); } public void testBuilderAddAllHandlesNullsCorrectly() { + { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.addAll((Collection) null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((Collection) null)); } - builder = ImmutableMultiset.builder(); + { + ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); List<@Nullable String> listWithNulls = asList("a", null, "b"); - try { - builder.addAll((List) listWithNulls); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows(NullPointerException.class, () -> builder.addAll((List) listWithNulls)); } - builder = ImmutableMultiset.builder(); + { + ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); Multiset<@Nullable String> multisetWithNull = LinkedHashMultiset.create(Arrays.<@Nullable String>asList("a", null, "b")); - try { - builder.addAll((Multiset) multisetWithNull); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { + assertThrows( + NullPointerException.class, () -> builder.addAll((Multiset) multisetWithNull)); } } public void testBuilderAddCopiesHandlesNullsCorrectly() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.addCopies(null, 2); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.addCopies(null, 2)); } public void testBuilderAddCopiesIllegal() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.addCopies("a", -2); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.addCopies("a", -2)); } public void testBuilderSetCountHandlesNullsCorrectly() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.setCount(null, 2); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.setCount(null, 2)); } public void testBuilderSetCountIllegal() { ImmutableMultiset.Builder builder = ImmutableMultiset.builder(); - try { - builder.setCount("a", -2); - fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.setCount("a", -2)); } @J2ktIncompatible diff --git a/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java b/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java index 5bf22d6b1d8e..66cee5226870 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableSetMultimapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER; import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE; @@ -93,11 +94,8 @@ public static Test suite() { } public void testBuilderWithExpectedKeysNegative() { - try { - ImmutableSetMultimap.builderWithExpectedKeys(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> ImmutableSetMultimap.builderWithExpectedKeys(-1)); } public void testBuilderWithExpectedKeysZero() { @@ -116,11 +114,7 @@ public void testBuilderWithExpectedKeysPositive() { public void testBuilderWithExpectedValuesPerKeyNegative() { ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder(); - try { - builder.expectedValuesPerKey(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.expectedValuesPerKey(-1)); } public void testBuilderWithExpectedValuesPerKeyZero() { @@ -140,11 +134,7 @@ public void testBuilderWithExpectedValuesPerKeyPositive() { public void testBuilderWithExpectedValuesPerKeyNegativeOrderValuesBy() { ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder().orderValuesBy(Ordering.natural()); - try { - builder.expectedValuesPerKey(-1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.expectedValuesPerKey(-1)); } public void testBuilderWithExpectedValuesPerKeyZeroOrderValuesBy() { @@ -203,16 +193,10 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = new Builder<>(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } private static class StringHolder { @@ -317,52 +301,23 @@ public void testBuilderPutNullKey() { Multimap<@Nullable String, Integer> toPut = LinkedListMultimap.create(); toPut.put(null, 1); ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll(null, Arrays.asList(1, 2, 3)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll(null, 1, 2, 3); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll((Multimap) toPut); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); + assertThrows(NullPointerException.class, () -> builder.putAll(null, Arrays.asList(1, 2, 3))); + assertThrows(NullPointerException.class, () -> builder.putAll(null, 1, 2, 3)); + assertThrows( + NullPointerException.class, () -> builder.putAll((Multimap) toPut)); } public void testBuilderPutNullValue() { Multimap toPut = LinkedListMultimap.create(); toPut.put("foo", null); ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder(); - try { - builder.put("foo", null); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll("foo", Arrays.asList(1, null, 3)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll("foo", 4, null, 6); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.putAll((Multimap) toPut); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("foo", null)); + assertThrows( + NullPointerException.class, () -> builder.putAll("foo", Arrays.asList(1, null, 3))); + assertThrows(NullPointerException.class, () -> builder.putAll("foo", 4, null, 6)); + assertThrows( + NullPointerException.class, () -> builder.putAll((Multimap) toPut)); } public void testBuilderOrderKeysBy() { @@ -497,21 +452,17 @@ public void testCopyOfImmutableSetMultimap() { public void testCopyOfNullKey() { HashMultimap<@Nullable String, Integer> input = HashMultimap.create(); input.put(null, 1); - try { - ImmutableSetMultimap.copyOf((Multimap) input); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableSetMultimap.copyOf((Multimap) input)); } public void testCopyOfNullValue() { HashMultimap input = HashMultimap.create(); input.putAll("foo", Arrays.<@Nullable Integer>asList(1, null, 3)); - try { - ImmutableSetMultimap.copyOf((Multimap) input); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableSetMultimap.copyOf((Multimap) input)); } public void testToImmutableSetMultimap() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java index 3e2c3b314ac5..9633caa5f7bf 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableSortedMapTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.truth.Truth.assertThat; @@ -157,11 +158,8 @@ public void testBuilder() { @SuppressWarnings("DoNotCall") public void testBuilder_orderEntriesByValueFails() { ImmutableSortedMap.Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.orderEntriesByValue(Ordering.natural()); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, () -> builder.orderEntriesByValue(Ordering.natural())); } public void testBuilder_withImmutableEntry() { @@ -174,16 +172,10 @@ public void testBuilder_withImmutableEntry() { public void testBuilder_withImmutableEntryAndNullContents() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.put(Maps.immutableEntry("one", (Integer) null)); - fail(); - } catch (NullPointerException expected) { - } - try { - builder.put(Maps.immutableEntry((String) null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry("one", (Integer) null))); + assertThrows( + NullPointerException.class, () -> builder.put(Maps.immutableEntry((String) null, 1))); } private static class StringHolder { @@ -245,38 +237,26 @@ public void testBuilderReuse() { public void testBuilderPutNullKey() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.put(null, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1)); } public void testBuilderPutNullValue() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.put("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> builder.put("one", null)); } public void testBuilderPutNullKeyViaPutAll() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.putAll(Collections.singletonMap(null, 1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap(null, 1))); } public void testBuilderPutNullValueViaPutAll() { Builder builder = ImmutableSortedMap.naturalOrder(); - try { - builder.putAll(Collections.singletonMap("one", null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> builder.putAll(Collections.singletonMap("one", null))); } public void testPuttingTheSameKeyTwiceThrowsOnBuild() { @@ -285,11 +265,7 @@ public void testPuttingTheSameKeyTwiceThrowsOnBuild() { .put("one", 1) .put("one", 2); // throwing on this line would be even better - try { - builder.build(); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> builder.build()); } public void testOf() { @@ -453,39 +429,20 @@ public void testOf() { public void testOfNullKey() { Integer n = null; - try { - ImmutableSortedMap.of(n, 1); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableSortedMap.of(n, 1)); - try { - ImmutableSortedMap.of("one", 1, null, 2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableSortedMap.of("one", 1, null, 2)); } public void testOfNullValue() { - try { - ImmutableSortedMap.of("one", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableSortedMap.of("one", null)); - try { - ImmutableSortedMap.of("one", 1, "two", null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> ImmutableSortedMap.of("one", 1, "two", null)); } + @SuppressWarnings("DistinctVarargsChecker") public void testOfWithDuplicateKey() { - try { - ImmutableSortedMap.of("one", 1, "one", 1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ImmutableSortedMap.of("one", 1, "one", 1)); } public void testCopyOfEmptyMap() { @@ -590,11 +547,7 @@ public void testCopyOfDuplicateKey() { new IntegerDiv10(35), "thirty five", new IntegerDiv10(12), "twelve"); - try { - ImmutableSortedMap.copyOf(original); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> ImmutableSortedMap.copyOf(original)); } public void testImmutableMapCopyOfImmutableSortedMap() { @@ -659,11 +612,9 @@ public void testToImmutableSortedMap() { public void testToImmutableSortedMap_exceptionOnDuplicateKey() { Collector, ?, ImmutableSortedMap> collector = ImmutableSortedMap.toImmutableSortedMap(Ordering.natural(), Entry::getKey, Entry::getValue); - try { - Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Stream.of(mapEntry("one", 1), mapEntry("one", 11)).collect(collector)); } public void testToImmutableSortedMapMerging() { @@ -707,11 +658,9 @@ public void testNullValuesInCopyOfMap() { source.put(k, k); } source.put(j, null); - try { - ImmutableSortedMap.copyOf((Map) source); - fail("Expected NullPointerException in copyOf(" + source + ")"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableSortedMap.copyOf((Map) source)); } } } @@ -724,11 +673,9 @@ public void testNullValuesInCopyOfEntries() { source.put(k, k); } source.put(j, null); - try { - ImmutableSortedMap.copyOf((Set>) source.entrySet()); - fail("Expected NullPointerException in copyOf(" + source.entrySet() + ")"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> ImmutableSortedMap.copyOf((Set>) source.entrySet())); } } } diff --git a/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java b/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java index 0e462b148cb2..acb41e9e4b65 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableSortedSetTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -264,20 +265,12 @@ public void testEmpty_subSet() { public void testEmpty_first() { SortedSet set = of(); - try { - set.first(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> set.first()); } public void testEmpty_last() { SortedSet set = of(); - try { - set.last(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> set.last()); } @J2ktIncompatible @@ -422,11 +415,7 @@ public void testOf_subSet() { assertSame(this.of(), set.subSet("a", "b")); assertSame(this.of(), set.subSet("g", "h")); assertSame(this.of(), set.subSet("c", "c")); - try { - set.subSet("e", "c"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> set.subSet("e", "c")); } @J2ktIncompatible @@ -545,11 +534,7 @@ public void testExplicit_subSet() { assertTrue(set.subSet("", "b").isEmpty()); assertTrue(set.subSet("vermont", "california").isEmpty()); assertTrue(set.subSet("aaa", "zzz").isEmpty()); - try { - set.subSet("quick", "the"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> set.subSet("quick", "the")); } public void testExplicit_first() { @@ -976,11 +961,7 @@ public void testLegacyComparable_builder_reverse() { @SuppressWarnings({"deprecation", "static-access", "DoNotCall"}) public void testBuilderMethod() { - try { - ImmutableSortedSet.builder(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> ImmutableSortedSet.builder()); } public void testAsList() { diff --git a/guava-tests/test/com/google/common/collect/ImmutableTableTest.java b/guava-tests/test/com/google/common/collect/ImmutableTableTest.java index 0322090ac6ab..ae7e372806a4 100644 --- a/guava-tests/test/com/google/common/collect/ImmutableTableTest.java +++ b/guava-tests/test/com/google/common/collect/ImmutableTableTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -88,24 +89,14 @@ public void testBuilder_withImmutableCell() { public void testBuilder_withImmutableCellAndNullContents() { ImmutableTable.Builder builder = new ImmutableTable.Builder<>(); - try { - builder.put(Tables.immutableCell((Character) null, 1, "foo")); - fail(); - } catch (NullPointerException e) { - // success - } - try { - builder.put(Tables.immutableCell('a', (Integer) null, "foo")); - fail(); - } catch (NullPointerException e) { - // success - } - try { - builder.put(Tables.immutableCell('a', 1, (String) null)); - fail(); - } catch (NullPointerException e) { - // success - } + assertThrows( + NullPointerException.class, + () -> builder.put(Tables.immutableCell((Character) null, 1, "foo"))); + assertThrows( + NullPointerException.class, + () -> builder.put(Tables.immutableCell('a', (Integer) null, "foo"))); + assertThrows( + NullPointerException.class, () -> builder.put(Tables.immutableCell('a', 1, (String) null))); } private static class StringHolder { @@ -150,34 +141,14 @@ public void testBuilder_noDuplicates() { new ImmutableTable.Builder() .put('a', 1, "foo") .put('a', 1, "bar"); - try { - builder.build(); - fail(); - } catch (IllegalArgumentException e) { - // success - } + assertThrows(IllegalArgumentException.class, () -> builder.build()); } public void testBuilder_noNulls() { ImmutableTable.Builder builder = new ImmutableTable.Builder<>(); - try { - builder.put(null, 1, "foo"); - fail(); - } catch (NullPointerException e) { - // success - } - try { - builder.put('a', null, "foo"); - fail(); - } catch (NullPointerException e) { - // success - } - try { - builder.put('a', 1, null); - fail(); - } catch (NullPointerException e) { - // success - } + assertThrows(NullPointerException.class, () -> builder.put(null, 1, "foo")); + assertThrows(NullPointerException.class, () -> builder.put('a', null, "foo")); + assertThrows(NullPointerException.class, () -> builder.put('a', 1, null)); } private static void validateTableCopies(Table original) { diff --git a/guava-tests/test/com/google/common/collect/IterablesTest.java b/guava-tests/test/com/google/common/collect/IterablesTest.java index 0f4d6750e0a2..97a0c732c3c4 100644 --- a/guava-tests/test/com/google/common/collect/IterablesTest.java +++ b/guava-tests/test/com/google/common/collect/IterablesTest.java @@ -18,6 +18,7 @@ import static com.google.common.collect.Iterables.skip; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; @@ -151,20 +152,12 @@ public void testGetOnlyElement_noDefault_valid() { public void testGetOnlyElement_noDefault_empty() { Iterable iterable = Collections.emptyList(); - try { - Iterables.getOnlyElement(iterable); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> Iterables.getOnlyElement(iterable)); } public void testGetOnlyElement_noDefault_multiple() { Iterable iterable = asList("foo", "bar"); - try { - Iterables.getOnlyElement(iterable); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterables.getOnlyElement(iterable)); } public void testGetOnlyElement_withDefault_singleton() { @@ -184,11 +177,7 @@ public void testGetOnlyElement_withDefault_empty_null() { public void testGetOnlyElement_withDefault_multiple() { Iterable iterable = asList("foo", "bar"); - try { - Iterables.getOnlyElement(iterable, "x"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterables.getOnlyElement(iterable, "x")); } @GwtIncompatible // Iterables.toArray(Iterable, Class) @@ -239,11 +228,8 @@ public void testFind() { Iterable list = newArrayList("cool", "pants"); assertEquals("cool", Iterables.find(list, Predicates.equalTo("cool"))); assertEquals("pants", Iterables.find(list, Predicates.equalTo("pants"))); - try { - Iterables.find(list, Predicates.alwaysFalse()); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows( + NoSuchElementException.class, () -> Iterables.find(list, Predicates.alwaysFalse())); assertEquals("cool", Iterables.find(list, Predicates.alwaysTrue())); assertCanIterateAgain(list); } @@ -344,11 +330,7 @@ public Integer apply(String from) { Iterator resultIterator = result.iterator(); resultIterator.next(); - try { - resultIterator.next(); - fail("Expected NFE"); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> resultIterator.next()); } public void testNullFriendlyTransform() { @@ -426,11 +408,7 @@ public void testConcatNullPointerException() { List list1 = newArrayList(1); List list2 = newArrayList(4); - try { - Iterables.concat(list1, null, list2); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Iterables.concat(list1, null, list2)); } public void testConcatPeformingFiniteCycle() { @@ -442,11 +420,7 @@ public void testConcatPeformingFiniteCycle() { public void testPartition_badSize() { Iterable source = Collections.singleton(1); - try { - Iterables.partition(source, 0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterables.partition(source, 0)); } public void testPartition_empty() { @@ -599,11 +573,7 @@ public void testLimit() { public void testLimit_illegalArgument() { List list = newArrayList("a", "b", "c"); - try { - Iterables.limit(list, -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterables.limit(list, -1)); } public void testIsEmpty() { @@ -654,31 +624,19 @@ public void testSkip_removal() { } catch (NoSuchElementException suppressed) { // We want remove() to fail even after a failed call to next(). } - try { - iterator.remove(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> iterator.remove()); } public void testSkip_allOfMutableList_modifiable() { List list = newArrayList("a", "b"); Iterator iterator = skip(list, 2).iterator(); - try { - iterator.remove(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> iterator.remove()); } public void testSkip_allOfImmutableList_modifiable() { List list = ImmutableList.of("a", "b"); Iterator iterator = skip(list, 2).iterator(); - try { - iterator.remove(); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); } @GwtIncompatible // slow (~35s) @@ -746,11 +704,7 @@ public void testSkip_structurallyModifiedSkipAllList() throws Exception { public void testSkip_illegalArgument() { List list = newArrayList("a", "b", "c"); - try { - skip(list, -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> skip(list, -1)); } private void testGetOnAbc(Iterable iterable) { @@ -807,12 +761,8 @@ public void testGet_emptyIterable() { } public void testGet_withDefault_negativePosition() { - try { - Iterables.get(newArrayList("a", "b", "c"), -1, "d"); - fail(); - } catch (IndexOutOfBoundsException expected) { - // pass - } + assertThrows( + IndexOutOfBoundsException.class, () -> Iterables.get(newArrayList("a", "b", "c"), -1, "d")); } public void testGet_withDefault_simple() { @@ -868,11 +818,7 @@ public void testGetLast_list() { public void testGetLast_emptyList() { List list = Collections.emptyList(); - try { - Iterables.getLast(list); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows(NoSuchElementException.class, () -> Iterables.getLast(list)); } public void testGetLast_sortedSet() { @@ -922,11 +868,7 @@ public void testGetLast_withDefault_not_empty_list() { public void testGetLast_emptySortedSet() { SortedSet sortedSet = ImmutableSortedSet.of(); - try { - Iterables.getLast(sortedSet); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows(NoSuchElementException.class, () -> Iterables.getLast(sortedSet)); } public void testGetLast_iterable() { @@ -936,11 +878,7 @@ public void testGetLast_iterable() { public void testGetLast_emptyIterable() { Set set = Sets.newHashSet(); - try { - Iterables.getLast(set); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows(NoSuchElementException.class, () -> Iterables.getLast(set)); } public void testUnmodifiableIterable() { @@ -948,11 +886,7 @@ public void testUnmodifiableIterable() { Iterable iterable = Iterables.unmodifiableIterable(list); Iterator iterator = iterable.iterator(); iterator.next(); - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); assertEquals("[a, b, c]", iterable.toString()); } @@ -1230,12 +1164,7 @@ public void testConsumingIterable_duelingIterators() { Iterator i2 = Iterables.consumingIterable(list).iterator(); i1.next(); - try { - i2.next(); - fail("Concurrent modification should throw an exception."); - } catch (ConcurrentModificationException cme) { - // Pass - } + assertThrows(ConcurrentModificationException.class, () -> i2.next()); } public void testConsumingIterable_queue_iterator() { @@ -1350,12 +1279,7 @@ public void testMergeSorted_empty() { // Verify Iterator iterator = iterable.iterator(); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail("next() on empty iterator should throw NoSuchElementException"); - } catch (NoSuchElementException e) { - // Huzzah! - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); } public void testMergeSorted_single_empty() { diff --git a/guava-tests/test/com/google/common/collect/IteratorsTest.java b/guava-tests/test/com/google/common/collect/IteratorsTest.java index ebed40f4df58..3b006c088da0 100644 --- a/guava-tests/test/com/google/common/collect/IteratorsTest.java +++ b/guava-tests/test/com/google/common/collect/IteratorsTest.java @@ -21,6 +21,7 @@ import static com.google.common.collect.Iterators.get; import static com.google.common.collect.Iterators.getLast; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.truth.Truth.assertThat; @@ -83,16 +84,8 @@ public static Test suite() { public void testEmptyIterator() { Iterator iterator = Iterators.emptyIterator(); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail("no exception thrown"); - } catch (NoSuchElementException expected) { - } - try { - iterator.remove(); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); } @SuppressWarnings("DoNotCall") @@ -102,46 +95,18 @@ public void testEmptyListIterator() { assertFalse(iterator.hasPrevious()); assertEquals(0, iterator.nextIndex()); assertEquals(-1, iterator.previousIndex()); - try { - iterator.next(); - fail("no exception thrown"); - } catch (NoSuchElementException expected) { - } - try { - iterator.previous(); - fail("no exception thrown"); - } catch (NoSuchElementException expected) { - } - try { - iterator.remove(); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } - try { - iterator.set("a"); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } - try { - iterator.add("a"); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); + assertThrows(NoSuchElementException.class, () -> iterator.previous()); + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); + assertThrows(UnsupportedOperationException.class, () -> iterator.set("a")); + assertThrows(UnsupportedOperationException.class, () -> iterator.add("a")); } public void testEmptyModifiableIterator() { Iterator iterator = Iterators.emptyModifiableIterator(); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail("Expected NoSuchElementException"); - } catch (NoSuchElementException expected) { - } - try { - iterator.remove(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); + assertThrows(IllegalStateException.class, () -> iterator.remove()); } public void testSize0() { @@ -188,45 +153,32 @@ public void testGetOnlyElement_noDefault_valid() { public void testGetOnlyElement_noDefault_empty() { Iterator iterator = Iterators.emptyIterator(); - try { - Iterators.getOnlyElement(iterator); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> Iterators.getOnlyElement(iterator)); } public void testGetOnlyElement_noDefault_moreThanOneLessThanFiveElements() { Iterator iterator = asList("one", "two").iterator(); - try { - Iterators.getOnlyElement(iterator); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: "); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> Iterators.getOnlyElement(iterator)); + assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: "); } public void testGetOnlyElement_noDefault_fiveElements() { Iterator iterator = asList("one", "two", "three", "four", "five").iterator(); - try { - Iterators.getOnlyElement(iterator); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("expected one element but was: "); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> Iterators.getOnlyElement(iterator)); + assertThat(expected) + .hasMessageThat() + .isEqualTo("expected one element but was: "); } public void testGetOnlyElement_noDefault_moreThanFiveElements() { Iterator iterator = asList("one", "two", "three", "four", "five", "six").iterator(); - try { - Iterators.getOnlyElement(iterator); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("expected one element but was: "); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> Iterators.getOnlyElement(iterator)); + assertThat(expected) + .hasMessageThat() + .isEqualTo("expected one element but was: "); } public void testGetOnlyElement_withDefault_singleton() { @@ -246,12 +198,9 @@ public void testGetOnlyElement_withDefault_empty_null() { public void testGetOnlyElement_withDefault_two() { Iterator iterator = asList("foo", "bar").iterator(); - try { - Iterators.getOnlyElement(iterator, "x"); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: "); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> Iterators.getOnlyElement(iterator, "x")); + assertThat(expected).hasMessageThat().isEqualTo("expected one element but was: "); } @GwtIncompatible // Iterators.toArray(Iterator, Class) @@ -375,11 +324,8 @@ public void testFind_lastElement() { public void testFind_notPresent() { Iterable list = Lists.newArrayList("cool", "pants"); Iterator iterator = list.iterator(); - try { - Iterators.find(iterator, Predicates.alwaysFalse()); - fail(); - } catch (NoSuchElementException e) { - } + assertThrows( + NoSuchElementException.class, () -> Iterators.find(iterator, Predicates.alwaysFalse())); assertFalse(iterator.hasNext()); } @@ -505,11 +451,7 @@ public Integer apply(String from) { }); result.next(); - try { - result.next(); - fail("Expected NFE"); - } catch (NumberFormatException expected) { - } + assertThrows(NumberFormatException.class, () -> result.next()); } public void testNullFriendlyTransform() { @@ -586,33 +528,21 @@ public void testCycleOfTwoWithRemove() { public void testCycleRemoveWithoutNext() { Iterator cycle = Iterators.cycle("a", "b"); assertTrue(cycle.hasNext()); - try { - cycle.remove(); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> cycle.remove()); } public void testCycleRemoveSameElementTwice() { Iterator cycle = Iterators.cycle("a", "b"); cycle.next(); cycle.remove(); - try { - cycle.remove(); - fail("no exception thrown"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> cycle.remove()); } public void testCycleWhenRemoveIsNotSupported() { Iterable iterable = asList("a", "b"); Iterator cycle = Iterators.cycle(iterable); cycle.next(); - try { - cycle.remove(); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> cycle.remove()); } public void testCycleRemoveAfterHasNext() { @@ -696,11 +626,7 @@ public void testCycleNoSuchElementException() { assertEquals("a", cycle.next()); cycle.remove(); assertFalse(cycle.hasNext()); - try { - cycle.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> cycle.next()); } @GwtIncompatible // unreasonably slow @@ -828,25 +754,17 @@ public void testConcatContainingNull() { Iterator result = Iterators.concat(input); assertEquals(1, (int) result.next()); assertEquals(2, (int) result.next()); - try { - result.hasNext(); - fail("no exception thrown"); - } catch (NullPointerException e) { - } - try { - result.next(); - fail("no exception thrown"); - } catch (NullPointerException e) { - } + assertThrows(NullPointerException.class, () -> result.hasNext()); + assertThrows(NullPointerException.class, () -> result.next()); // There is no way to get "through" to the 3. Buh-bye } public void testConcatVarArgsContainingNull() { - try { - Iterators.concat(iterateOver(1, 2), null, iterateOver(3), iterateOver(4), iterateOver(5)); - fail("no exception thrown"); - } catch (NullPointerException e) { - } + assertThrows( + NullPointerException.class, + () -> + Iterators.concat( + iterateOver(1, 2), null, iterateOver(3), iterateOver(4), iterateOver(5))); } public void testConcatNested_appendToEnd() { @@ -977,11 +895,7 @@ public void testElementsEqual() { public void testPartition_badSize() { Iterator source = Iterators.singletonIterator(1); - try { - Iterators.partition(source, 0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterators.partition(source, 0)); } public void testPartition_empty() { @@ -1048,11 +962,7 @@ public void testPartitionRandomAccess() { public void testPaddedPartition_badSize() { Iterator source = Iterators.singletonIterator(1); - try { - Iterators.paddedPartition(source, 0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterators.paddedPartition(source, 0)); } public void testPaddedPartition_empty() { @@ -1119,16 +1029,8 @@ public void testForArrayEmpty() { String[] array = new String[0]; Iterator iterator = Iterators.forArray(array); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException expected) { - } - try { - Iterators.forArrayWithPosition(array, 1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); + assertThrows(IndexOutOfBoundsException.class, () -> Iterators.forArrayWithPosition(array, 1)); } @SuppressWarnings("DoNotCall") @@ -1138,18 +1040,10 @@ public void testForArrayTypical() { assertTrue(iterator.hasNext()); assertEquals("foo", iterator.next()); assertTrue(iterator.hasNext()); - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); assertEquals("bar", iterator.next()); assertFalse(iterator.hasNext()); - try { - iterator.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); } public void testForArrayWithPosition() { @@ -1165,16 +1059,8 @@ public void testForArrayWithPosition() { public void testForArrayLengthWithPositionBoundaryCases() { String[] array = {"foo", "bar"}; assertFalse(Iterators.forArrayWithPosition(array, 2).hasNext()); - try { - Iterators.forArrayWithPosition(array, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } - try { - Iterators.forArrayWithPosition(array, 3); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> Iterators.forArrayWithPosition(array, -1)); + assertThrows(IndexOutOfBoundsException.class, () -> Iterators.forArrayWithPosition(array, 3)); } @GwtIncompatible // unreasonably slow @@ -1198,11 +1084,7 @@ public void testForEnumerationEmpty() { Iterator iter = Iterators.forEnumeration(enumer); assertFalse(iter.hasNext()); - try { - iter.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> iter.next()); } @SuppressWarnings("DoNotCall") @@ -1213,17 +1095,9 @@ public void testForEnumerationSingleton() { assertTrue(iter.hasNext()); assertTrue(iter.hasNext()); assertEquals(1, (int) iter.next()); - try { - iter.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iter.remove()); assertFalse(iter.hasNext()); - try { - iter.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> iter.next()); } public void testForEnumerationTypical() { @@ -1244,11 +1118,7 @@ public void testAsEnumerationEmpty() { Enumeration enumer = Iterators.asEnumeration(iter); assertFalse(enumer.hasMoreElements()); - try { - enumer.nextElement(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> enumer.nextElement()); } public void testAsEnumerationSingleton() { @@ -1259,11 +1129,7 @@ public void testAsEnumerationSingleton() { assertTrue(enumer.hasMoreElements()); assertEquals(1, (int) enumer.nextElement()); assertFalse(enumer.hasMoreElements()); - try { - enumer.nextElement(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> enumer.nextElement()); } public void testAsEnumerationTypical() { @@ -1303,11 +1169,7 @@ public void testToStringEmptyIterator() { @SuppressWarnings("JUnitIncompatibleType") // Fails with j2kt. public void testLimit() { List list = newArrayList(); - try { - Iterators.limit(list.iterator(), -1); - fail("expected exception"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Iterators.limit(list.iterator(), -1)); assertFalse(Iterators.limit(list.iterator(), 0).hasNext()); assertFalse(Iterators.limit(list.iterator(), 1).hasNext()); @@ -1377,11 +1239,7 @@ public void testGetLast_basic() { public void testGetLast_exception() { List list = newArrayList(); - try { - getLast(list.iterator()); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> getLast(list.iterator())); } public void testGetLast_withDefault_singleton() { @@ -1418,11 +1276,7 @@ public void testGet_atSize() { list.add("a"); list.add("b"); Iterator iterator = list.iterator(); - try { - get(iterator, 2); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, 2)); assertFalse(iterator.hasNext()); } @@ -1431,33 +1285,21 @@ public void testGet_pastEnd() { list.add("a"); list.add("b"); Iterator iterator = list.iterator(); - try { - get(iterator, 5); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, 5)); assertFalse(iterator.hasNext()); } public void testGet_empty() { List list = newArrayList(); Iterator iterator = list.iterator(); - try { - get(iterator, 0); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, 0)); assertFalse(iterator.hasNext()); } public void testGet_negativeIndex() { List list = newArrayList("a", "b", "c"); Iterator iterator = list.iterator(); - try { - get(iterator, -1); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, -1)); } public void testGet_withDefault_basic() { @@ -1492,12 +1334,7 @@ public void testGet_withDefault_negativeIndex() { list.add("a"); list.add("b"); Iterator iterator = list.iterator(); - try { - get(iterator, -1, "c"); - fail(); - } catch (IndexOutOfBoundsException expected) { - // pass - } + assertThrows(IndexOutOfBoundsException.class, () -> get(iterator, -1, "c")); assertTrue(iterator.hasNext()); } @@ -1522,11 +1359,7 @@ public void testAdvance_pastEnd() { public void testAdvance_illegalArgument() { List list = newArrayList("a", "b", "c"); Iterator iterator = list.iterator(); - try { - advance(iterator, -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> advance(iterator, -1)); } public void testFrequency() { @@ -1655,12 +1488,7 @@ public void testConsumingIterator_duelingIterators() { Iterator i2 = Iterators.consumingIterator(list.iterator()); i1.next(); - try { - i2.next(); - fail("Concurrent modification should throw an exception."); - } catch (ConcurrentModificationException cme) { - // Pass - } + assertThrows(ConcurrentModificationException.class, () -> i2.next()); } public void testIndexOf_consumedData() { diff --git a/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java b/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java index 1a1382bd801b..8d663424a0fd 100644 --- a/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/LinkedHashMultimapTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.Helpers.mapEntry; @@ -270,17 +271,9 @@ public void testCreateFromSizes() { } public void testCreateFromIllegalSizes() { - try { - LinkedHashMultimap.create(-20, 15); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> LinkedHashMultimap.create(-20, 15)); - try { - LinkedHashMultimap.create(20, -15); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> LinkedHashMultimap.create(20, -15)); } @GwtIncompatible // unreasonably slow diff --git a/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java b/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java index 524740a3df5d..92de76cdb071 100644 --- a/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java +++ b/guava-tests/test/com/google/common/collect/LinkedListMultimapTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; @@ -146,11 +147,7 @@ public void testCreateFromSize() { } public void testCreateFromIllegalSize() { - try { - LinkedListMultimap.create(-20); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> LinkedListMultimap.create(-20)); } public void testLinkedGetAdd() { @@ -295,18 +292,15 @@ public void testLinkedAsMapEntries() { map.put("foo", 2); map.put("bar", 3); Iterator>> entries = map.asMap().entrySet().iterator(); - Entry> entry = entries.next(); - assertEquals("bar", entry.getKey()); - assertThat(entry.getValue()).containsExactly(1, 3).inOrder(); - try { - entry.setValue(Arrays.asList()); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + Entry> barEntry = entries.next(); + assertEquals("bar", barEntry.getKey()); + assertThat(barEntry.getValue()).containsExactly(1, 3).inOrder(); + assertThrows( + UnsupportedOperationException.class, () -> barEntry.setValue(Arrays.asList())); entries.remove(); // clear - entry = entries.next(); - assertEquals("foo", entry.getKey()); - assertThat(entry.getValue()).contains(2); + Entry> fooEntry = entries.next(); + assertEquals("foo", fooEntry.getKey()); + assertThat(fooEntry.getValue()).contains(2); assertFalse(entries.hasNext()); assertEquals("{foo=[2]}", map.toString()); } diff --git a/guava-tests/test/com/google/common/collect/ListsTest.java b/guava-tests/test/com/google/common/collect/ListsTest.java index b3e92599af72..d89365b66f3c 100644 --- a/guava-tests/test/com/google/common/collect/ListsTest.java +++ b/guava-tests/test/com/google/common/collect/ListsTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -330,11 +331,7 @@ public void testNewArrayListWithCapacity() { } public void testNewArrayListWithCapacity_negative() { - try { - Lists.newArrayListWithCapacity(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Lists.newArrayListWithCapacity(-1)); } public void testNewArrayListWithExpectedSize() { @@ -346,11 +343,7 @@ public void testNewArrayListWithExpectedSize() { } public void testNewArrayListWithExpectedSize_negative() { - try { - Lists.newArrayListWithExpectedSize(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Lists.newArrayListWithExpectedSize(-1)); } public void testNewArrayListVarArgs() { @@ -433,18 +426,10 @@ public void testArraysAsList() { assertEquals("FOO", otherWay.get(0)); // But it can't grow - try { - otherWay.add("nope"); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> otherWay.add("nope")); // And it can't shrink - try { - otherWay.remove(2); - fail("no exception thrown"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> otherWay.remove(2)); } @J2ktIncompatible @@ -658,11 +643,8 @@ public void testCartesianProduct_unrelatedTypes() { public void testCartesianProductTooBig() { List list = Collections.nCopies(10000, "foo"); - try { - Lists.cartesianProduct(list, list, list, list, list); - fail("Expected IAE"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> Lists.cartesianProduct(list, list, list, list, list)); } public void testTransformHashCodeRandomAccess() { @@ -771,20 +753,18 @@ public void testTransformListIteratorSequential() { } public void testTransformPreservesIOOBEsThrownByFunction() { - try { - Lists.transform( - ImmutableList.of("foo", "bar"), - new Function() { - @Override - public String apply(String input) { - throw new IndexOutOfBoundsException(); - } - }) - .toArray(); - fail(); - } catch (IndexOutOfBoundsException expected) { - // success - } + assertThrows( + IndexOutOfBoundsException.class, + () -> + Lists.transform( + ImmutableList.of("foo", "bar"), + new Function() { + @Override + public String apply(String input) { + throw new IndexOutOfBoundsException(); + } + }) + .toArray()); } private static void assertTransformListIterator(List list) { @@ -900,11 +880,7 @@ private static void assertTransformIterator(List list) { public void testPartition_badSize() { List source = Collections.singletonList(1); - try { - Lists.partition(source, 0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Lists.partition(source, 0)); } public void testPartition_empty() { diff --git a/guava-tests/test/com/google/common/collect/MapMakerTest.java b/guava-tests/test/com/google/common/collect/MapMakerTest.java index 563c9802f8aa..0bc48dde11b2 100644 --- a/guava-tests/test/com/google/common/collect/MapMakerTest.java +++ b/guava-tests/test/com/google/common/collect/MapMakerTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; import com.google.common.annotations.GwtCompatible; @@ -62,11 +63,7 @@ public T apply(T key) { public void testInitialCapacity_negative() { MapMaker maker = new MapMaker(); - try { - maker.initialCapacity(-1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> maker.initialCapacity(-1)); } // TODO(cpovirk): enable when ready (apparently after a change to our GWT emulation) diff --git a/guava-tests/test/com/google/common/collect/MapsTest.java b/guava-tests/test/com/google/common/collect/MapsTest.java index 76f9faa627e6..d84925cc3965 100644 --- a/guava-tests/test/com/google/common/collect/MapsTest.java +++ b/guava-tests/test/com/google/common/collect/MapsTest.java @@ -19,6 +19,7 @@ import static com.google.common.collect.Maps.transformEntries; import static com.google.common.collect.Maps.transformValues; import static com.google.common.collect.Maps.unmodifiableNavigableMap; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; @@ -101,11 +102,7 @@ public void testHashMapGeneralizesTypes() { } public void testCapacityForNegativeSizeFails() { - try { - Maps.capacity(-1); - fail("Negative expected size must result in IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Maps.capacity(-1)); } /** @@ -335,11 +332,9 @@ public void testEnumMap() { } public void testEnumMapNullClass() { - try { - Maps.newEnumMap((Class) null); - fail("no exception thrown"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Maps.newEnumMap((Class) null)); } public void testEnumMapWithInitialEnumMap() { @@ -365,11 +360,7 @@ public void testEnumMapWithInitialMap() { public void testEnumMapWithInitialEmptyMap() { Map original = Maps.newHashMap(); - try { - Maps.newEnumMap(original); - fail("Empty map must result in an IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Maps.newEnumMap(original)); } public void testToStringImplWithNullKeys() throws Exception { @@ -627,21 +618,9 @@ public void testSortedMapDifferenceImmutable() { Maps.immutableEntry(3, ValueDifferenceImpl.create("c", "f")), Maps.immutableEntry(5, ValueDifferenceImpl.create("e", "g"))) .inOrder(); - try { - diff1.entriesInCommon().put(7, "x"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - diff1.entriesOnlyOnLeft().put(7, "x"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - diff1.entriesOnlyOnRight().put(7, "x"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> diff1.entriesInCommon().put(7, "x")); + assertThrows(UnsupportedOperationException.class, () -> diff1.entriesOnlyOnLeft().put(7, "x")); + assertThrows(UnsupportedOperationException.class, () -> diff1.entriesOnlyOnRight().put(7, "x")); } public void testSortedMapDifferenceEquals() { @@ -766,26 +745,11 @@ public void testAsMapSortedWritesThrough() { public void testAsMapSortedSubViewKeySetsDoNotSupportAdd() { SortedMap map = Maps.asMap(new NonNavigableSortedSet(), LENGTH_FUNCTION); - try { - map.subMap("a", "z").keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.tailMap("a").keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.headMap("r").keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.headMap("r").tailMap("m").keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.subMap("a", "z").keySet().add("a")); + assertThrows(UnsupportedOperationException.class, () -> map.tailMap("a").keySet().add("a")); + assertThrows(UnsupportedOperationException.class, () -> map.headMap("r").keySet().add("a")); + assertThrows( + UnsupportedOperationException.class, () -> map.headMap("r").tailMap("m").keySet().add("a")); } public void testAsMapSortedEmpty() { @@ -892,31 +856,17 @@ public void testAsMapNavigableWritesThrough() { @GwtIncompatible // NavigableMap public void testAsMapNavigableSubViewKeySetsDoNotSupportAdd() { NavigableMap map = Maps.asMap(Sets.newTreeSet(), LENGTH_FUNCTION); - try { - map.descendingKeySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.subMap("a", true, "z", false).keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.tailMap("a", true).keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.headMap("r", true).keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } - try { - map.headMap("r", false).tailMap("m", true).keySet().add("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.descendingKeySet().add("a")); + assertThrows( + UnsupportedOperationException.class, + () -> map.subMap("a", true, "z", false).keySet().add("a")); + assertThrows( + UnsupportedOperationException.class, () -> map.tailMap("a", true).keySet().add("a")); + assertThrows( + UnsupportedOperationException.class, () -> map.headMap("r", true).keySet().add("a")); + assertThrows( + UnsupportedOperationException.class, + () -> map.headMap("r", false).tailMap("m", true).keySet().add("a")); } @GwtIncompatible // NavigableMap @@ -957,20 +907,14 @@ public void testToMapWithDuplicateKeys() { public void testToMapWithNullKeys() { Iterable<@Nullable String> strings = Arrays.asList("one", null, "three"); - try { - Maps.toMap((Iterable) strings, Functions.constant("foo")); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Maps.toMap((Iterable) strings, Functions.constant("foo"))); } public void testToMapWithNullValues() { Iterable strings = ImmutableList.of("one", "two", "three"); - try { - Maps.toMap(strings, Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Maps.toMap(strings, Functions.constant(null))); } private static final ImmutableBiMap INT_TO_STRING_MAP = @@ -1008,33 +952,27 @@ public void testUniqueIndexIterator() { /** Can't create the map if more than one value maps to the same key. */ public void testUniqueIndexDuplicates() { - try { - Map unused = - Maps.uniqueIndex(ImmutableSet.of("one", "uno"), Functions.constant(1)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("Multimaps.index"); - } + IllegalArgumentException expected = + assertThrows( + IllegalArgumentException.class, + () -> Maps.uniqueIndex(ImmutableSet.of("one", "uno"), Functions.constant(1))); + assertThat(expected.getMessage()).contains("Multimaps.index"); } /** Null values are not allowed. */ public void testUniqueIndexNullValue() { List<@Nullable String> listWithNull = Lists.newArrayList((String) null); - try { - Maps.uniqueIndex((List) listWithNull, Functions.constant(1)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Maps.uniqueIndex((List) listWithNull, Functions.constant(1))); } /** Null keys aren't allowed either. */ public void testUniqueIndexNullKey() { List oneStringList = Lists.newArrayList("foo"); - try { - Maps.uniqueIndex(oneStringList, Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Maps.uniqueIndex(oneStringList, Functions.constant(null))); } @J2ktIncompatible @@ -1101,11 +1039,7 @@ public Enumeration propertyNames() { properties.setProperty("first", "true"); properties.setProperty("second", "null"); - try { - Maps.fromProperties(properties); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Maps.fromProperties(properties)); } @J2ktIncompatible @@ -1121,11 +1055,7 @@ public Enumeration propertyNames() { } }; - try { - Maps.fromProperties(properties); - fail(); - } catch (ClassCastException expected) { - } + assertThrows(ClassCastException.class, () -> Maps.fromProperties(properties)); } public void testAsConverter_nominal() throws Exception { @@ -1156,11 +1086,7 @@ public void testAsConverter_noMapping() throws Exception { "one", 1, "two", 2); Converter converter = Maps.asConverter(biMap); - try { - converter.convert("three"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> converter.convert("three")); } public void testAsConverter_nullConversions() throws Exception { @@ -1181,11 +1107,7 @@ public void testAsConverter_isAView() throws Exception { assertEquals((Integer) 1, converter.convert("one")); assertEquals((Integer) 2, converter.convert("two")); - try { - converter.convert("three"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> converter.convert("three")); biMap.put("three", 3); @@ -1199,11 +1121,9 @@ public void testAsConverter_withNullMapping() throws Exception { biMap.put("one", 1); biMap.put("two", 2); biMap.put("three", null); - try { - Maps.asConverter((BiMap) biMap).convert("three"); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> Maps.asConverter((BiMap) biMap).convert("three")); } public void testAsConverter_toString() { @@ -1242,115 +1162,44 @@ public void testUnmodifiableBiMap() { assertEquals(true, unmod.inverse().get("four").equals(4)); /* UnsupportedOperationException on direct modifications. */ - try { - unmod.put(4, "four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.forcePut(4, "four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.putAll(Collections.singletonMap(4, "four")); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.replaceAll((k, v) -> v); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.putIfAbsent(3, "three"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.replace(3, "three", "four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.replace(3, "four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.computeIfAbsent(3, (k) -> k + "three"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.computeIfPresent(4, (k, v) -> v); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.compute(4, (k, v) -> v); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.merge(4, "four", (k, v) -> v); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - unmod.clear(); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> unmod.put(4, "four")); + assertThrows(UnsupportedOperationException.class, () -> unmod.forcePut(4, "four")); + assertThrows( + UnsupportedOperationException.class, + () -> unmod.putAll(Collections.singletonMap(4, "four"))); + assertThrows(UnsupportedOperationException.class, () -> unmod.replaceAll((k, v) -> v)); + assertThrows(UnsupportedOperationException.class, () -> unmod.putIfAbsent(3, "three")); + assertThrows(UnsupportedOperationException.class, () -> unmod.replace(3, "three", "four")); + assertThrows(UnsupportedOperationException.class, () -> unmod.replace(3, "four")); + assertThrows( + UnsupportedOperationException.class, () -> unmod.computeIfAbsent(3, (k) -> k + "three")); + assertThrows(UnsupportedOperationException.class, () -> unmod.computeIfPresent(4, (k, v) -> v)); + assertThrows(UnsupportedOperationException.class, () -> unmod.compute(4, (k, v) -> v)); + assertThrows(UnsupportedOperationException.class, () -> unmod.merge(4, "four", (k, v) -> v)); + assertThrows(UnsupportedOperationException.class, () -> unmod.clear()); /* UnsupportedOperationException on indirect modifications. */ BiMap inverse = unmod.inverse(); - try { - inverse.put("four", 4); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - inverse.forcePut("four", 4); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - inverse.putAll(Collections.singletonMap("four", 4)); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> inverse.put("four", 4)); + assertThrows(UnsupportedOperationException.class, () -> inverse.forcePut("four", 4)); + assertThrows( + UnsupportedOperationException.class, + () -> inverse.putAll(Collections.singletonMap("four", 4))); Set values = unmod.values(); - try { - values.remove("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> values.remove("four")); Set> entries = unmod.entrySet(); Entry entry = entries.iterator().next(); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); @SuppressWarnings("unchecked") Entry entry2 = (Entry) entries.toArray()[0]; - try { - entry2.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> entry2.setValue("four")); } public void testImmutableEntry() { Entry e = Maps.immutableEntry("foo", 1); assertEquals("foo", e.getKey()); assertEquals(1, (int) e.getValue()); - try { - e.setValue(2); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> e.setValue(2)); assertEquals("foo=1", e.toString()); assertEquals(101575, e.hashCode()); } @@ -1360,11 +1209,7 @@ public void testImmutableEntryNull() { Maps.immutableEntry((String) null, (Integer) null); assertNull(e.getKey()); assertNull(e.getValue()); - try { - e.setValue(null); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> e.setValue(null)); assertEquals("null=null", e.toString()); assertEquals(0, e.hashCode()); } @@ -1557,92 +1402,64 @@ public void testUnmodifiableNavigableMap() { ensureNotDirectlyModifiable(unmod.tailMap(2, true)); Collection values = unmod.values(); - try { - values.add("4"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - values.remove("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - values.removeAll(Collections.singleton("four")); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - values.retainAll(Collections.singleton("four")); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - Iterator iterator = values.iterator(); - iterator.next(); - iterator.remove(); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> values.add("4")); + assertThrows(UnsupportedOperationException.class, () -> values.remove("four")); + assertThrows( + UnsupportedOperationException.class, () -> values.removeAll(Collections.singleton("four"))); + assertThrows( + UnsupportedOperationException.class, () -> values.retainAll(Collections.singleton("four"))); + assertThrows( + UnsupportedOperationException.class, + () -> { + Iterator iterator = values.iterator(); + iterator.next(); + iterator.remove(); + }); Set> entries = unmod.entrySet(); - try { - Iterator> iterator = entries.iterator(); - iterator.next(); - iterator.remove(); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, + () -> { + Iterator> iterator = entries.iterator(); + iterator.next(); + iterator.remove(); + }); + { Entry entry = entries.iterator().next(); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.lowerEntry(1); + { + Entry entry = unmod.lowerEntry(1); assertNull(entry); - entry = unmod.floorEntry(2); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { } - entry = unmod.ceilingEntry(2); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.floorEntry(2); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.lowerEntry(2); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.ceilingEntry(2); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.higherEntry(2); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.lowerEntry(2); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.firstEntry(); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.higherEntry(2); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - entry = unmod.lastEntry(); - try { - entry.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.firstEntry(); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } - @SuppressWarnings("unchecked") - Entry entry2 = (Entry) entries.toArray()[0]; - try { - entry2.setValue("four"); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { + { + Entry entry = unmod.lastEntry(); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); + } + { + @SuppressWarnings("unchecked") + Entry entry = (Entry) entries.toArray()[0]; + assertThrows(UnsupportedOperationException.class, () -> entry.setValue("four")); } } @@ -1795,11 +1612,7 @@ public void testSubMap_unnaturalOrdering() { .put(10, 0) .build(); - try { - Maps.subMap(map, Range.closed(4, 8)); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Maps.subMap(map, Range.closed(4, 8))); // These results are all incorrect, but there's no way (short of iterating over the result) // to verify that with an arbitrary ordering or comparator. diff --git a/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java b/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java index 3583c5675848..f83afa1837a1 100644 --- a/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java +++ b/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -196,23 +198,13 @@ public void testTransformIdentityFunctionEquality() { public void testTransformPutEntryIsUnsupported() { Map map = Maps.transformValues(ImmutableMap.of("a", 1), Functions.toStringFunction()); - try { - map.put("b", "2"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.put("b", "2")); - try { - map.putAll(ImmutableMap.of("b", "2")); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.putAll(ImmutableMap.of("b", "2"))); - try { - map.entrySet().iterator().next().setValue("one"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows( + UnsupportedOperationException.class, + () -> map.entrySet().iterator().next().setValue("one")); } public void testTransformRemoveEntry() { diff --git a/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java b/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java index ca19020ab9fd..2edc6043f892 100644 --- a/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java +++ b/guava-tests/test/com/google/common/collect/MinMaxPriorityQueueTest.java @@ -19,6 +19,7 @@ import static com.google.common.base.Objects.equal; import static com.google.common.collect.Platform.reduceExponentIfGwt; import static com.google.common.collect.Platform.reduceIterationsIfGwt; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -326,11 +327,7 @@ public void testIteratorPastEndException() { assertTrue("Iterator has reached end prematurely", it.hasNext()); it.next(); it.next(); - try { - it.next(); - fail("No exception thrown when iterating past end of heap"); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> it.next()); } public void testIteratorConcurrentModification() { @@ -341,11 +338,7 @@ public void testIteratorConcurrentModification() { it.next(); it.next(); mmHeap.remove(4); - try { - it.next(); - fail("No exception thrown when iterating a modified heap"); - } catch (ConcurrentModificationException expected) { - } + assertThrows(ConcurrentModificationException.class, () -> it.next()); } /** Tests a failure caused by fix to childless uncle issue. */ @@ -879,26 +872,12 @@ public void testIsEvenLevel() { // since isEvenLevel adds 1, we need to do - 2. assertTrue(MinMaxPriorityQueue.isEvenLevel((1 << 31) - 2)); assertTrue(MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE - 1)); - try { - MinMaxPriorityQueue.isEvenLevel((1 << 31) - 1); - fail("Should overflow"); - } catch (IllegalStateException expected) { - } - try { - MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE); - fail("Should overflow"); - } catch (IllegalStateException expected) { - } - try { - MinMaxPriorityQueue.isEvenLevel(1 << 31); - fail("Should be negative"); - } catch (IllegalStateException expected) { - } - try { - MinMaxPriorityQueue.isEvenLevel(Integer.MIN_VALUE); - fail("Should be negative"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel((1 << 31) - 1)); + assertThrows( + IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel(Integer.MAX_VALUE)); + assertThrows(IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel(1 << 31)); + assertThrows( + IllegalStateException.class, () -> MinMaxPriorityQueue.isEvenLevel(Integer.MIN_VALUE)); } @J2ktIncompatible diff --git a/guava-tests/test/com/google/common/collect/MoreCollectorsTest.java b/guava-tests/test/com/google/common/collect/MoreCollectorsTest.java index 9244c0c11fb8..ae61fd5207cf 100644 --- a/guava-tests/test/com/google/common/collect/MoreCollectorsTest.java +++ b/guava-tests/test/com/google/common/collect/MoreCollectorsTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -42,45 +43,33 @@ public void testToOptionalSingleton() { public void testToOptionalNull() { Stream<@Nullable Object> stream = Stream.of((Object) null); - try { - stream.collect(MoreCollectors.toOptional()); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> stream.collect(MoreCollectors.toOptional())); } public void testToOptionalMultiple() { - try { - Stream.of(1, 2).collect(MoreCollectors.toOptional()); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("1, 2"); - } + IllegalArgumentException expected = + assertThrows( + IllegalArgumentException.class, + () -> Stream.of(1, 2).collect(MoreCollectors.toOptional())); + assertThat(expected.getMessage()).contains("1, 2"); } public void testToOptionalMultipleWithNull() { - try { - Stream.of(1, null).collect(MoreCollectors.toOptional()); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> Stream.of(1, null).collect(MoreCollectors.toOptional())); } public void testToOptionalMany() { - try { - Stream.of(1, 2, 3, 4, 5, 6).collect(MoreCollectors.toOptional()); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("1, 2, 3, 4, 5, ..."); - } + IllegalArgumentException expected = + assertThrows( + IllegalArgumentException.class, + () -> Stream.of(1, 2, 3, 4, 5, 6).collect(MoreCollectors.toOptional())); + assertThat(expected.getMessage()).contains("1, 2, 3, 4, 5, ..."); } public void testOnlyElement() { - try { - Stream.empty().collect(MoreCollectors.onlyElement()); - fail("Expected NoSuchElementException"); - } catch (NoSuchElementException expected) { - } + assertThrows( + NoSuchElementException.class, () -> Stream.empty().collect(MoreCollectors.onlyElement())); } public void testOnlyElementSingleton() { @@ -93,20 +82,18 @@ public void testOnlyElementNull() { } public void testOnlyElementMultiple() { - try { - Stream.of(1, 2).collect(MoreCollectors.onlyElement()); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("1, 2"); - } + IllegalArgumentException expected = + assertThrows( + IllegalArgumentException.class, + () -> Stream.of(1, 2).collect(MoreCollectors.onlyElement())); + assertThat(expected.getMessage()).contains("1, 2"); } public void testOnlyElementMany() { - try { - Stream.of(1, 2, 3, 4, 5, 6).collect(MoreCollectors.onlyElement()); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("1, 2, 3, 4, 5, ..."); - } + IllegalArgumentException expected = + assertThrows( + IllegalArgumentException.class, + () -> Stream.of(1, 2, 3, 4, 5, 6).collect(MoreCollectors.onlyElement())); + assertThat(expected.getMessage()).contains("1, 2, 3, 4, 5, ..."); } } diff --git a/guava-tests/test/com/google/common/collect/MultimapsTest.java b/guava-tests/test/com/google/common/collect/MultimapsTest.java index 3e79c97d99da..b78f6251af96 100644 --- a/guava-tests/test/com/google/common/collect/MultimapsTest.java +++ b/guava-tests/test/com/google/common/collect/MultimapsTest.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Maps.immutableEntry; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.testing.Helpers.mapEntry; import static com.google.common.collect.testing.Helpers.nefariousMapEntry; @@ -312,25 +313,13 @@ public void testUnmodifiableMultimapEntries() { Multimap mod = HashMultimap.create(); Multimap unmod = Multimaps.unmodifiableMultimap(mod); mod.put("foo", 1); - Entry entry = unmod.entries().iterator().next(); - try { - entry.setValue(2); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - entry = (Entry) unmod.entries().toArray()[0]; - try { - entry.setValue(2); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + Entry fromIterator = unmod.entries().iterator().next(); + assertThrows(UnsupportedOperationException.class, () -> fromIterator.setValue(2)); + Entry fromToArray = (Entry) unmod.entries().toArray()[0]; + assertThrows(UnsupportedOperationException.class, () -> fromToArray.setValue(2)); Entry[] array = (Entry[]) new Entry[2]; assertSame(array, unmod.entries().toArray(array)); - try { - array[0].setValue(2); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> array[0].setValue(2)); assertFalse(unmod.entries().contains(nefariousMapEntry("pwnd", 2))); assertFalse(unmod.keys().contains("pwnd")); } @@ -496,26 +485,14 @@ public void testForMap() { assertTrue(multimapView.containsEntry("bar", 2)); assertEquals(Collections.singleton(1), multimapView.get("foo")); assertEquals(Collections.singleton(2), multimapView.get("bar")); - try { - multimapView.put("baz", 3); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - multimapView.putAll("baz", Collections.singleton(3)); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - multimapView.putAll(multimap); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - multimapView.replaceValues("foo", Collections.emptySet()); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> multimapView.put("baz", 3)); + assertThrows( + UnsupportedOperationException.class, + () -> multimapView.putAll("baz", Collections.singleton(3))); + assertThrows(UnsupportedOperationException.class, () -> multimapView.putAll(multimap)); + assertThrows( + UnsupportedOperationException.class, + () -> multimapView.replaceValues("foo", Collections.emptySet())); multimapView.remove("bar", 2); assertFalse(multimapView.containsKey("bar")); assertFalse(map.containsKey("bar")); @@ -668,18 +645,10 @@ public boolean addAll(Collection collection) { Map> map = Maps.newEnumMap(Color.class); Multimap multimap = Multimaps.newMultimap(map, factory); - try { - multimap.put(Color.BLUE, -1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> multimap.put(Color.BLUE, -1)); multimap.put(Color.RED, 1); multimap.put(Color.BLUE, 2); - try { - multimap.put(Color.GREEN, -1); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> multimap.put(Color.GREEN, -1)); assertThat(multimap.entries()) .containsExactly(Maps.immutableEntry(Color.RED, 1), Maps.immutableEntry(Color.BLUE, 2)); } @@ -892,20 +861,15 @@ public Integer apply(String input) { public void testIndex_nullValue() { List<@Nullable Integer> values = Arrays.asList(1, null); - try { - Multimaps.index((List) values, Functions.identity()); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Multimaps.index((List) values, Functions.identity())); } public void testIndex_nullKey() { List values = Arrays.asList(1, 2); - try { - Multimaps.index(values, Functions.constant(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, () -> Multimaps.index(values, Functions.constant(null))); } @GwtIncompatible(value = "untested") @@ -1039,11 +1003,8 @@ public void testFilteredKeysSetMultimapReplaceValues() { assertEquals(ImmutableSet.of(), filtered.replaceValues("baz", ImmutableSet.of())); - try { - filtered.replaceValues("baz", ImmutableSet.of(5)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> filtered.replaceValues("baz", ImmutableSet.of(5))); } public void testFilteredKeysSetMultimapGetBadValue() { @@ -1057,16 +1018,8 @@ public void testFilteredKeysSetMultimapGetBadValue() { Multimaps.filterKeys(multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); Set bazSet = filtered.get("baz"); assertThat(bazSet).isEmpty(); - try { - bazSet.add(5); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - try { - bazSet.addAll(ImmutableSet.of(6, 7)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> bazSet.add(5)); + assertThrows(IllegalArgumentException.class, () -> bazSet.addAll(ImmutableSet.of(6, 7))); } public void testFilteredKeysListMultimapGetBadValue() { @@ -1080,26 +1033,10 @@ public void testFilteredKeysListMultimapGetBadValue() { Multimaps.filterKeys(multimap, Predicates.in(ImmutableSet.of("foo", "bar"))); List bazList = filtered.get("baz"); assertThat(bazList).isEmpty(); - try { - bazList.add(5); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - try { - bazList.add(0, 6); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - try { - bazList.addAll(ImmutableList.of(7, 8)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } - try { - bazList.addAll(0, ImmutableList.of(9, 10)); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> bazList.add(5)); + assertThrows(IllegalArgumentException.class, () -> bazList.add(0, 6)); + assertThrows(IllegalArgumentException.class, () -> bazList.addAll(ImmutableList.of(7, 8))); + assertThrows(IllegalArgumentException.class, () -> bazList.addAll(0, ImmutableList.of(9, 10))); } @J2ktIncompatible diff --git a/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java b/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java index 792520f8881b..447fffbce795 100644 --- a/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java +++ b/guava-tests/test/com/google/common/collect/MultisetsImmutableEntryTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multiset.Entry; import java.util.Collections; @@ -77,10 +79,6 @@ public void testHashCodeNull() { } public void testNegativeCount() { - try { - entry("foo", -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> entry("foo", -1)); } } diff --git a/guava-tests/test/com/google/common/collect/OrderingTest.java b/guava-tests/test/com/google/common/collect/OrderingTest.java index d0d65662f5c3..51ae6bac5b5b 100644 --- a/guava-tests/test/com/google/common/collect/OrderingTest.java +++ b/guava-tests/test/com/google/common/collect/OrderingTest.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Lists.newArrayList; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.testing.SerializableTester.reserialize; import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static com.google.common.truth.Truth.assertThat; @@ -111,21 +112,9 @@ public void testComplicatedOrderingExample() { public void testNatural() { Ordering comparator = Ordering.natural(); Helpers.testComparator(comparator, Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE); - try { - comparator.compare(1, null); - fail(); - } catch (NullPointerException expected) { - } - try { - comparator.compare(null, 2); - fail(); - } catch (NullPointerException expected) { - } - try { - comparator.compare(null, null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> comparator.compare(1, null)); + assertThrows(NullPointerException.class, () -> comparator.compare(null, 2)); + assertThrows(NullPointerException.class, () -> comparator.compare(null, null)); assertSame(comparator, reserialize(comparator)); assertEquals("Ordering.natural()", comparator.toString()); } @@ -146,24 +135,18 @@ public void testFrom() { public void testExplicit_none() { Comparator c = Ordering.explicit(Collections.emptyList()); - try { - c.compare(0, 0); - fail(); - } catch (IncomparableValueException expected) { - assertEquals(0, expected.value); - } + IncomparableValueException expected = + assertThrows(IncomparableValueException.class, () -> c.compare(0, 0)); + assertEquals(0, expected.value); reserializeAndAssert(c); } public void testExplicit_one() { Comparator c = Ordering.explicit(0); assertEquals(0, c.compare(0, 0)); - try { - c.compare(0, 1); - fail(); - } catch (IncomparableValueException expected) { - assertEquals(1, expected.value); - } + IncomparableValueException expected = + assertThrows(IncomparableValueException.class, () -> c.compare(0, 1)); + assertEquals(1, expected.value); reserializeAndAssert(c); assertEquals("Ordering.explicit([0])", c.toString()); } @@ -173,12 +156,9 @@ public void testExplicitMax_b297601553() { // TODO(b/297601553): this should probably throw an CCE since 0 isn't explicitly listed assertEquals(0, (int) c.max(asList(0))); - try { - c.max(asList(0, 1)); - fail(); - } catch (IncomparableValueException expected) { - assertEquals(0, expected.value); - } + IncomparableValueException expected = + assertThrows(IncomparableValueException.class, () -> c.max(asList(0, 1))); + assertEquals(0, expected.value); } public void testExplicit_two() { @@ -186,12 +166,9 @@ public void testExplicit_two() { assertEquals(0, c.compare(5, 5)); assertTrue(c.compare(5, 42) > 0); assertTrue(c.compare(42, 5) < 0); - try { - c.compare(5, 666); - fail(); - } catch (IncomparableValueException expected) { - assertEquals(666, expected.value); - } + IncomparableValueException expected = + assertThrows(IncomparableValueException.class, () -> c.compare(5, 666)); + assertEquals(666, expected.value); new EqualsTester() .addEqualityGroup(c, Ordering.explicit(42, 5)) .addEqualityGroup(Ordering.explicit(5, 42)) @@ -210,11 +187,7 @@ public void testExplicit_sortingExample() { @SuppressWarnings("DistinctVarargsChecker") // test of buggy call public void testExplicit_withDuplicates() { - try { - Ordering.explicit(1, 2, 3, 4, 2); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Ordering.explicit(1, 2, 3, 4, 2)); } // A more limited test than the one that follows, but this one uses the @@ -486,11 +459,12 @@ public void testImmutableSortedCopy() { numberOrdering.immutableSortedCopy(Collections.emptyList())); List<@Nullable Integer> listWithNull = Arrays.asList(5, 3, null, 9); - try { - Ordering.natural().nullsFirst().immutableSortedCopy((List) listWithNull); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> + Ordering.natural() + .nullsFirst() + .immutableSortedCopy((List) listWithNull)); } public void testIsOrdered() { @@ -542,19 +516,15 @@ public void testLeastOfIterator_empty_1() { } public void testLeastOfIterable_simple_negativeOne() { - try { - numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> numberOrdering.leastOf(Arrays.asList(3, 4, 5, -1), -1)); } public void testLeastOfIterator_simple_negativeOne() { - try { - numberOrdering.leastOf(Iterators.forArray(3, 4, 5, -1), -1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> numberOrdering.leastOf(Iterators.forArray(3, 4, 5, -1), -1)); } public void testLeastOfIterable_singleton_0() { diff --git a/guava-tests/test/com/google/common/collect/PeekingIteratorTest.java b/guava-tests/test/com/google/common/collect/PeekingIteratorTest.java index 22686633c6ae..508ee8efc10c 100644 --- a/guava-tests/test/com/google/common/collect/PeekingIteratorTest.java +++ b/guava-tests/test/com/google/common/collect/PeekingIteratorTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Iterators.peekingIterator; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static java.util.Collections.emptyList; @@ -114,12 +115,7 @@ public void testPeekOnEmptyList() { Iterator iterator = list.iterator(); PeekingIterator peekingIterator = Iterators.peekingIterator(iterator); - try { - peekingIterator.peek(); - fail("Should throw NoSuchElementException if nothing to peek()"); - } catch (NoSuchElementException e) { - /* expected */ - } + assertThrows(NoSuchElementException.class, () -> peekingIterator.peek()); } public void testPeekDoesntChangeIteration() { @@ -145,24 +141,9 @@ public void testPeekDoesntChangeIteration() { assertEquals( "next() should still return last element after peeking", "C", peekingIterator.next()); - try { - peekingIterator.peek(); - fail("Should throw exception if no next to peek()"); - } catch (NoSuchElementException e) { - /* expected */ - } - try { - peekingIterator.peek(); - fail("Should continue to throw exception if no next to peek()"); - } catch (NoSuchElementException e) { - /* expected */ - } - try { - peekingIterator.next(); - fail("next() should still throw exception after the end of iteration"); - } catch (NoSuchElementException e) { - /* expected */ - } + assertThrows(NoSuchElementException.class, () -> peekingIterator.peek()); + assertThrows(NoSuchElementException.class, () -> peekingIterator.peek()); + assertThrows(NoSuchElementException.class, () -> peekingIterator.next()); } public void testCantRemoveAfterPeek() { @@ -174,12 +155,7 @@ public void testCantRemoveAfterPeek() { assertEquals("B", peekingIterator.peek()); /* Should complain on attempt to remove() after peek(). */ - try { - peekingIterator.remove(); - fail("remove() should throw IllegalStateException after a peek()"); - } catch (IllegalStateException e) { - /* expected */ - } + assertThrows(IllegalStateException.class, () -> peekingIterator.remove()); assertEquals( "After remove() throws exception, peek should still be ok", "B", peekingIterator.peek()); diff --git a/guava-tests/test/com/google/common/collect/RangeTest.java b/guava-tests/test/com/google/common/collect/RangeTest.java index 7ea3b0bed73e..ffd73e0886f5 100644 --- a/guava-tests/test/com/google/common/collect/RangeTest.java +++ b/guava-tests/test/com/google/common/collect/RangeTest.java @@ -19,6 +19,7 @@ import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.DiscreteDomain.integers; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.testing.SerializableTester.reserializeAndAssert; import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; @@ -58,16 +59,8 @@ public void testOpen() { } public void testOpen_invalid() { - try { - Range.open(4, 3); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - Range.open(3, 3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.open(4, 3)); + assertThrows(IllegalArgumentException.class, () -> Range.open(3, 3)); } public void testClosed() { @@ -85,11 +78,7 @@ public void testClosed() { } public void testClosed_invalid() { - try { - Range.closed(4, 3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.closed(4, 3)); } public void testOpenClosed() { @@ -294,6 +283,7 @@ public void testOrderingCuts() { Helpers.testCompareToAndEquals(ImmutableList.of(a, b, c, d, e, f)); } + @SuppressWarnings("DistinctVarargsChecker") public void testContainsAll() { Range range = Range.closed(3, 5); assertTrue(range.containsAll(asList(3, 3, 4, 5))); @@ -348,43 +338,35 @@ public void testIntersection_empty() { Range range = Range.closedOpen(3, 3); assertEquals(range, range.intersection(range)); - try { - range.intersection(Range.open(3, 5)); - fail(); - } catch (IllegalArgumentException expected) { - // TODO(kevinb): convert the rest of this file to Truth someday - assertThat(expected).hasMessageThat().contains("connected"); - } - try { - range.intersection(Range.closed(0, 2)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.open(3, 5))); + assertThat(expected).hasMessageThat().contains("connected"); + expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.closed(0, 2))); + assertThat(expected).hasMessageThat().contains("connected"); } public void testIntersection_deFactoEmpty() { - Range range = Range.open(3, 4); - assertEquals(range, range.intersection(range)); + { + Range range = Range.open(3, 4); + assertEquals(range, range.intersection(range)); - assertEquals(Range.openClosed(3, 3), range.intersection(Range.atMost(3))); - assertEquals(Range.closedOpen(4, 4), range.intersection(Range.atLeast(4))); + assertEquals(Range.openClosed(3, 3), range.intersection(Range.atMost(3))); + assertEquals(Range.closedOpen(4, 4), range.intersection(Range.atLeast(4))); - try { - range.intersection(Range.lessThan(3)); - fail(); - } catch (IllegalArgumentException expected) { + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.lessThan(3))); assertThat(expected).hasMessageThat().contains("connected"); - } - try { - range.intersection(Range.greaterThan(4)); - fail(); - } catch (IllegalArgumentException expected) { + expected = + assertThrows( + IllegalArgumentException.class, () -> range.intersection(Range.greaterThan(4))); assertThat(expected).hasMessageThat().contains("connected"); } - range = Range.closed(3, 4); - assertEquals(Range.openClosed(4, 4), range.intersection(Range.greaterThan(4))); + { + Range range = Range.closed(3, 4); + assertEquals(Range.openClosed(4, 4), range.intersection(Range.greaterThan(4))); + } } public void testIntersection_singleton() { @@ -399,30 +381,21 @@ public void testIntersection_singleton() { assertEquals(Range.closedOpen(3, 3), range.intersection(Range.lessThan(3))); assertEquals(Range.openClosed(3, 3), range.intersection(Range.greaterThan(3))); - try { - range.intersection(Range.atLeast(4)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } - try { - range.intersection(Range.atMost(2)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.atLeast(4))); + assertThat(expected).hasMessageThat().contains("connected"); + expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.atMost(2))); + assertThat(expected).hasMessageThat().contains("connected"); } public void testIntersection_general() { Range range = Range.closed(4, 8); // separate below - try { - range.intersection(Range.closed(0, 2)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } + IllegalArgumentException expected = + assertThrows(IllegalArgumentException.class, () -> range.intersection(Range.closed(0, 2))); + assertThat(expected).hasMessageThat().contains("connected"); // adjacent below assertEquals(Range.closedOpen(4, 4), range.intersection(Range.closedOpen(2, 4))); @@ -458,58 +431,28 @@ public void testIntersection_general() { assertEquals(Range.openClosed(8, 8), range.intersection(Range.openClosed(8, 10))); // separate above - try { - range.intersection(Range.closed(10, 12)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected).hasMessageThat().contains("connected"); - } + expected = + assertThrows( + IllegalArgumentException.class, () -> range.intersection(Range.closed(10, 12))); + assertThat(expected).hasMessageThat().contains("connected"); } public void testGap_overlapping() { Range range = Range.closedOpen(3, 5); - try { - range.gap(Range.closed(4, 6)); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - range.gap(Range.closed(2, 4)); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - range.gap(Range.closed(2, 3)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> range.gap(Range.closed(4, 6))); + assertThrows(IllegalArgumentException.class, () -> range.gap(Range.closed(2, 4))); + assertThrows(IllegalArgumentException.class, () -> range.gap(Range.closed(2, 3))); } public void testGap_invalidRangesWithInfinity() { - try { - Range.atLeast(1).gap(Range.atLeast(2)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.atLeast(1).gap(Range.atLeast(2))); - try { - Range.atLeast(2).gap(Range.atLeast(1)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.atLeast(2).gap(Range.atLeast(1))); - try { - Range.atMost(1).gap(Range.atMost(2)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.atMost(1).gap(Range.atMost(2))); - try { - Range.atMost(2).gap(Range.atMost(1)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Range.atMost(2).gap(Range.atMost(1))); } public void testGap_connectedAdjacentYieldsEmpty() { @@ -668,26 +611,14 @@ public void testEncloseAll() { } public void testEncloseAll_empty() { - try { - Range.encloseAll(ImmutableSet.of()); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> Range.encloseAll(ImmutableSet.of())); } public void testEncloseAll_nullValue() { List<@Nullable Integer> nullFirst = Lists.newArrayList(null, 0); - try { - Range.encloseAll((List) nullFirst); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Range.encloseAll((List) nullFirst)); List<@Nullable Integer> nullNotFirst = Lists.newArrayList(0, null); - try { - Range.encloseAll((List) nullNotFirst); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Range.encloseAll((List) nullNotFirst)); } public void testEquivalentFactories() { diff --git a/guava-tests/test/com/google/common/collect/ReflectionFreeAssertThrows.java b/guava-tests/test/com/google/common/collect/ReflectionFreeAssertThrows.java new file mode 100644 index 000000000000..e24b5b1027b9 --- /dev/null +++ b/guava-tests/test/com/google/common/collect/ReflectionFreeAssertThrows.java @@ -0,0 +1,160 @@ +/* + * 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.collect; + +import com.google.common.annotations.GwtCompatible; +import com.google.common.annotations.GwtIncompatible; +import com.google.common.annotations.J2ktIncompatible; +import com.google.common.base.Predicate; +import com.google.common.base.VerifyException; +import com.google.common.collect.Ordering.IncomparableValueException; +import com.google.common.collect.TestExceptions.SomeCheckedException; +import com.google.common.collect.TestExceptions.SomeError; +import com.google.common.collect.TestExceptions.SomeOtherCheckedException; +import com.google.common.collect.TestExceptions.SomeUncheckedException; +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(IncomparableValueException.class, e -> e instanceof IncomparableValueException) + .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/collect/SetsTest.java b/guava-tests/test/com/google/common/collect/SetsTest.java index b60c0477e4b1..a338c3384e97 100644 --- a/guava-tests/test/com/google/common/collect/SetsTest.java +++ b/guava-tests/test/com/google/common/collect/SetsTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.collect.Iterables.unmodifiableIterable; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Sets.newEnumSet; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; @@ -338,16 +339,8 @@ public void testImmutableEnumSet() { Set units = Sets.immutableEnumSet(SomeEnum.D, SomeEnum.B); assertThat(units).containsExactly(SomeEnum.B, SomeEnum.D).inOrder(); - try { - units.remove(SomeEnum.B); - fail("ImmutableEnumSet should throw an exception on remove()"); - } catch (UnsupportedOperationException expected) { - } - try { - units.add(SomeEnum.C); - fail("ImmutableEnumSet should throw an exception on add()"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> units.remove(SomeEnum.B)); + assertThrows(UnsupportedOperationException.class, () -> units.add(SomeEnum.C)); } public void testToImmutableEnumSet() { @@ -681,11 +674,7 @@ public void testComplementOfEmptyEnumSetWithoutType() { @GwtIncompatible // complementOf public void testComplementOfEmptySetWithoutTypeDoesntWork() { Set set = Collections.emptySet(); - try { - Sets.complementOf(set); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Sets.complementOf(set)); } @J2ktIncompatible @@ -715,11 +704,7 @@ public void testNewSetFromMapSerialization() { public void testNewSetFromMapIllegal() { Map map = new LinkedHashMap<>(); map.put(2, true); - try { - Sets.newSetFromMap(map); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Sets.newSetFromMap(map)); } /** The 0-ary cartesian product is a single empty list. */ @@ -823,11 +808,8 @@ public void testCartesianProduct_unrelatedTypes() { public void testCartesianProductTooBig() { Set set = ContiguousSet.create(Range.closed(0, 10000), DiscreteDomain.integers()); - try { - Sets.cartesianProduct(set, set, set, set, set); - fail("Expected IAE"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> Sets.cartesianProduct(set, set, set, set, set)); } public void testCartesianProduct_hashCode() { @@ -912,11 +894,7 @@ public void testPowerSetIteration_manual() { assertEquals(ImmutableSet.of(3, 2), i.next()); assertEquals(ImmutableSet.of(3, 2, 1), i.next()); assertFalse(i.hasNext()); - try { - i.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> i.next()); } @GwtIncompatible // too slow for GWT @@ -968,27 +946,24 @@ public void testPowerSetSize() { } public void testPowerSetCreationErrors() { - try { - Set> unused = - powerSet( - newHashSet( - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', - 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5')); - fail(); - } catch (IllegalArgumentException expected) { - } - - try { - Set> unused = powerSet(ContiguousSet.closed(0, Integer.MAX_VALUE / 2)); - fail(); - } catch (IllegalArgumentException expected) { - } - - try { - powerSet(singleton(null)); - fail(); - } catch (NullPointerException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> { + Set> unused = + powerSet( + newHashSet( + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', + '5')); + }); + + assertThrows( + IllegalArgumentException.class, + () -> { + Set> unused = powerSet(ContiguousSet.closed(0, Integer.MAX_VALUE / 2)); + }); + + assertThrows(NullPointerException.class, () -> powerSet(singleton(null))); } public void testPowerSetEqualsAndHashCode_verifyAgainstHashSet() { @@ -1185,21 +1160,10 @@ public void testUnmodifiableNavigableSet() { /* UnsupportedOperationException on indirect modifications. */ NavigableSet reverse = unmod.descendingSet(); - try { - reverse.add(4); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - reverse.addAll(Collections.singleton(4)); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } - try { - reverse.remove(4); - fail("UnsupportedOperationException expected"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> reverse.add(4)); + assertThrows( + UnsupportedOperationException.class, () -> reverse.addAll(Collections.singleton(4))); + assertThrows(UnsupportedOperationException.class, () -> reverse.remove(4)); } void ensureNotDirectlyModifiable(SortedSet unmod) { @@ -1338,11 +1302,7 @@ public void testSubSet_unnaturalOrdering() { ImmutableSortedSet set = ImmutableSortedSet.reverseOrder().add(2, 4, 6, 8, 10).build(); - try { - Sets.subSet(set, Range.closed(4, 8)); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> Sets.subSet(set, Range.closed(4, 8))); // These results are all incorrect, but there's no way (short of iterating over the result) // to verify that with an arbitrary ordering or comparator. diff --git a/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java b/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java index d7a281ae8e33..7dd66df559da 100644 --- a/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java +++ b/guava-tests/test/com/google/common/collect/SimpleAbstractMultisetTest.java @@ -15,6 +15,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -68,6 +69,7 @@ protected Multiset create(String[] elements) { return suite; } + @SuppressWarnings("ModifiedButNotUsed") public void testFastAddAllMultiset() { final AtomicInteger addCalls = new AtomicInteger(); Multiset multiset = @@ -87,11 +89,7 @@ public int add(String element, int occurrences) { public void testRemoveUnsupported() { Multiset multiset = new NoRemoveMultiset<>(); multiset.add("a"); - try { - multiset.remove("a"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> multiset.remove("a")); assertTrue(multiset.contains("a")); } diff --git a/guava-tests/test/com/google/common/collect/TableCollectionTest.java b/guava-tests/test/com/google/common/collect/TableCollectionTest.java index 1a956f74c473..c12e3f77af09 100644 --- a/guava-tests/test/com/google/common/collect/TableCollectionTest.java +++ b/guava-tests/test/com/google/common/collect/TableCollectionTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -853,11 +854,7 @@ public void testRemove() { assertFalse(map.containsKey(keyToRemove)); assertEquals(initialSize - 1, map.size()); } else { - try { - map.remove(keyToRemove); - fail("Expected UnsupportedOperationException."); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> map.remove(keyToRemove)); } assertInvariants(map); } diff --git a/guava-tests/test/com/google/common/collect/TableCollectorsTest.java b/guava-tests/test/com/google/common/collect/TableCollectorsTest.java index cfd9161e98df..53737a318fa9 100644 --- a/guava-tests/test/com/google/common/collect/TableCollectorsTest.java +++ b/guava-tests/test/com/google/common/collect/TableCollectorsTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.Tables.immutableCell; import com.google.common.annotations.GwtCompatible; @@ -56,48 +57,47 @@ public void testToImmutableTable() { public void testToImmutableTableConflict() { Collector, ?, ImmutableTable> collector = TableCollectors.toImmutableTable(Cell::getRowKey, Cell::getColumnKey, Cell::getValue); - try { - Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", 2)).collect(collector); - fail("Expected IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> + Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", 2)) + .collect(collector)); } public void testToImmutableTableNullRowKey() { Collector, ?, ImmutableTable> collector = TableCollectors.toImmutableTable(t -> null, Cell::getColumnKey, Cell::getValue); - try { - Stream.of(immutableCell("one", "uno", 1)).collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Stream.of(immutableCell("one", "uno", 1)).collect(collector)); } public void testToImmutableTableNullColumnKey() { Collector, ?, ImmutableTable> collector = TableCollectors.toImmutableTable(Cell::getRowKey, t -> null, Cell::getValue); - try { - Stream.of(immutableCell("one", "uno", 1)).collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Stream.of(immutableCell("one", "uno", 1)).collect(collector)); } public void testToImmutableTableNullValue() { - Collector, ?, ImmutableTable> collector = - TableCollectors.toImmutableTable(Cell::getRowKey, Cell::getColumnKey, t -> null); - try { - Stream.of(immutableCell("one", "uno", 1)).collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { + { + Collector, ?, ImmutableTable> + collector = + TableCollectors.toImmutableTable(Cell::getRowKey, Cell::getColumnKey, t -> null); + assertThrows( + NullPointerException.class, + () -> Stream.of(immutableCell("one", "uno", 1)).collect(collector)); } - collector = - TableCollectors.toImmutableTable(Cell::getRowKey, Cell::getColumnKey, Cell::getValue); - try { - Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", (Integer) null)) - .collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { + { + Collector, ?, ImmutableTable> + collector = + TableCollectors.toImmutableTable(Cell::getRowKey, Cell::getColumnKey, Cell::getValue); + assertThrows( + NullPointerException.class, + () -> + Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", (Integer) null)) + .collect(collector)); } } @@ -124,43 +124,42 @@ public void testToImmutableTableMergingNullRowKey() { Collector, ?, ImmutableTable> collector = TableCollectors.toImmutableTable( t -> null, Cell::getColumnKey, Cell::getValue, Integer::sum); - try { - Stream.of(immutableCell("one", "uno", 1)).collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Stream.of(immutableCell("one", "uno", 1)).collect(collector)); } public void testToImmutableTableMergingNullColumnKey() { Collector, ?, ImmutableTable> collector = TableCollectors.toImmutableTable(Cell::getRowKey, t -> null, Cell::getValue, Integer::sum); - try { - Stream.of(immutableCell("one", "uno", 1)).collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> Stream.of(immutableCell("one", "uno", 1)).collect(collector)); } public void testToImmutableTableMergingNullValue() { - Collector, ?, ImmutableTable> collector = - TableCollectors.toImmutableTable( - Cell::getRowKey, Cell::getColumnKey, t -> null, Integer::sum); - try { - Stream.of(immutableCell("one", "uno", 1)).collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { + { + Collector, ?, ImmutableTable> + collector = + TableCollectors.toImmutableTable( + Cell::getRowKey, Cell::getColumnKey, t -> null, Integer::sum); + assertThrows( + NullPointerException.class, + () -> Stream.of(immutableCell("one", "uno", 1)).collect(collector)); } - collector = - TableCollectors.toImmutableTable( - Cell::getRowKey, - Cell::getColumnKey, - Cell::getValue, - (i, j) -> MoreObjects.firstNonNull(i, 0) + MoreObjects.firstNonNull(j, 0)); - try { - Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", (Integer) null)) - .collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { + { + Collector, ?, ImmutableTable> + collector = + TableCollectors.toImmutableTable( + Cell::getRowKey, + Cell::getColumnKey, + Cell::getValue, + (i, j) -> MoreObjects.firstNonNull(i, 0) + MoreObjects.firstNonNull(j, 0)); + assertThrows( + NullPointerException.class, + () -> + Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", (Integer) null)) + .collect(collector)); } } @@ -168,11 +167,11 @@ public void testToImmutableTableMergingNullMerge() { Collector, ?, ImmutableTable> collector = TableCollectors.toImmutableTable( Cell::getRowKey, Cell::getColumnKey, Cell::getValue, (v1, v2) -> null); - try { - Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", 2)).collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows( + NullPointerException.class, + () -> + Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", 2)) + .collect(collector)); } public void testToTable() { @@ -224,23 +223,21 @@ public void testToTableNullValues() { ArrayTable.create(ImmutableList.of("one"), ImmutableList.of("uno")); return (Table) table; }); - try { - Cell cell = immutableCell("one", "uno", null); - Stream.of((Cell) cell).collect(collector); - fail("Expected NullPointerException"); - } catch (NullPointerException expected) { - } + Cell cell = immutableCell("one", "uno", null); + assertThrows( + NullPointerException.class, + () -> Stream.of((Cell) cell).collect(collector)); } public void testToTableConflict() { Collector, ?, Table> collector = TableCollectors.toTable( Cell::getRowKey, Cell::getColumnKey, Cell::getValue, HashBasedTable::create); - try { - Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", 2)).collect(collector); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows( + IllegalStateException.class, + () -> + Stream.of(immutableCell("one", "uno", 1), immutableCell("one", "uno", 2)) + .collect(collector)); } public void testToTableMerging() { diff --git a/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java b/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java index 8039b1dec5c1..23b802246754 100644 --- a/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java +++ b/guava-tests/test/com/google/common/collect/TablesTransformValuesTest.java @@ -17,6 +17,7 @@ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -61,11 +62,7 @@ public void testNullPointerInstance() {} // put() and putAll() aren't supported. @Override public void testPut() { - try { - table.put("foo", 1, 'a'); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> table.put("foo", 1, 'a')); assertSize(0); } @@ -76,11 +73,7 @@ public void testPutAllTable() { other.put("foo", 1, 'd'); other.put("bar", 2, 'e'); other.put("cat", 2, 'f'); - try { - table.putAll(other); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> table.putAll(other)); assertEquals((Character) 'a', table.get("foo", 1)); assertEquals((Character) 'b', table.get("bar", 1)); assertEquals((Character) 'c', table.get("foo", 3)); diff --git a/guava-tests/test/com/google/common/collect/TestExceptions.java b/guava-tests/test/com/google/common/collect/TestExceptions.java new file mode 100644 index 000000000000..f7ca37fbd944 --- /dev/null +++ b/guava-tests/test/com/google/common/collect/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.collect; + +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/collect/TopKSelectorTest.java b/guava-tests/test/com/google/common/collect/TopKSelectorTest.java index 05ecb2040fe4..9793dbd77e20 100644 --- a/guava-tests/test/com/google/common/collect/TopKSelectorTest.java +++ b/guava-tests/test/com/google/common/collect/TopKSelectorTest.java @@ -16,6 +16,7 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; @@ -36,26 +37,11 @@ public class TopKSelectorTest extends TestCase { public void testNegativeK() { - try { - TopKSelector.least(-1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - TopKSelector.greatest(-1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - TopKSelector.least(-1, Ordering.natural()); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - TopKSelector.greatest(-1, Ordering.natural()); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> TopKSelector.least(-1)); + assertThrows(IllegalArgumentException.class, () -> TopKSelector.greatest(-1)); + assertThrows(IllegalArgumentException.class, () -> TopKSelector.least(-1, Ordering.natural())); + assertThrows( + IllegalArgumentException.class, () -> TopKSelector.greatest(-1, Ordering.natural())); } public void testZeroK() { diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableIteratorTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableIteratorTest.java index e2e432fe5299..fad660a0c6f6 100644 --- a/guava-tests/test/com/google/common/collect/UnmodifiableIteratorTest.java +++ b/guava-tests/test/com/google/common/collect/UnmodifiableIteratorTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.NoSuchElementException; @@ -54,10 +56,6 @@ public String next() { assertTrue(iterator.hasNext()); assertEquals("a", iterator.next()); - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); } } diff --git a/guava-tests/test/com/google/common/collect/UnmodifiableListIteratorTest.java b/guava-tests/test/com/google/common/collect/UnmodifiableListIteratorTest.java index 130ef6b7cdca..02cf78e2baa7 100644 --- a/guava-tests/test/com/google/common/collect/UnmodifiableListIteratorTest.java +++ b/guava-tests/test/com/google/common/collect/UnmodifiableListIteratorTest.java @@ -16,6 +16,8 @@ package com.google.common.collect; +import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows; + import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.ListIterator; @@ -36,11 +38,7 @@ public void testRemove() { assertTrue(iterator.hasNext()); assertEquals("a", iterator.next()); - try { - iterator.remove(); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.remove()); } @SuppressWarnings("DoNotCall") @@ -51,11 +49,7 @@ public void testAdd() { assertEquals("a", iterator.next()); assertEquals("b", iterator.next()); assertEquals("b", iterator.previous()); - try { - iterator.add("c"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.add("c")); } @SuppressWarnings("DoNotCall") @@ -66,11 +60,7 @@ public void testSet() { assertEquals("a", iterator.next()); assertEquals("b", iterator.next()); assertEquals("b", iterator.previous()); - try { - iterator.set("c"); - fail(); - } catch (UnsupportedOperationException expected) { - } + assertThrows(UnsupportedOperationException.class, () -> iterator.set("c")); } UnmodifiableListIterator create() {