Skip to content

Commit b0461b7

Browse files
cpovirkGoogle Java Core Libraries
authored andcommitted
Use assertThrows even in GWT/J2CL/J2KT-compatible code, common.cache+io+math+reflect+testing edition.
(continuing the path started in cl/675634517) And address a few other warnings. RELNOTES=n/a PiperOrigin-RevId: 687302660
1 parent 6082782 commit b0461b7

40 files changed

+2070
-1494
lines changed

android/guava-testlib/test/com/google/common/testing/EqualsTesterTest.java

Lines changed: 20 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616

1717
package com.google.common.testing;
1818

19+
import static com.google.common.testing.ReflectionFreeAssertThrows.assertThrows;
20+
import static com.google.common.truth.Truth.assertThat;
21+
1922
import com.google.common.annotations.GwtCompatible;
2023
import com.google.common.base.Preconditions;
2124
import com.google.common.collect.ImmutableList;
@@ -51,29 +54,21 @@ public void setUp() throws Exception {
5154

5255
/** Test null reference yields error */
5356
public void testAddNullReference() {
54-
try {
55-
equalsTester.addEqualityGroup((Object) null);
56-
fail("Should fail on null reference");
57-
} catch (NullPointerException e) {
58-
}
57+
assertThrows(NullPointerException.class, () -> equalsTester.addEqualityGroup((Object) null));
5958
}
6059

6160
/** Test equalObjects after adding multiple instances at once with a null */
6261
public void testAddTwoEqualObjectsAtOnceWithNull() {
63-
try {
64-
equalsTester.addEqualityGroup(reference, equalObject1, null);
65-
fail("Should fail on null equal object");
66-
} catch (NullPointerException e) {
67-
}
62+
assertThrows(
63+
NullPointerException.class,
64+
() -> equalsTester.addEqualityGroup(reference, equalObject1, null));
6865
}
6966

7067
/** Test adding null equal object yields error */
7168
public void testAddNullEqualObject() {
72-
try {
73-
equalsTester.addEqualityGroup(reference, (Object[]) null);
74-
fail("Should fail on null equal object");
75-
} catch (NullPointerException e) {
76-
}
69+
assertThrows(
70+
NullPointerException.class,
71+
() -> equalsTester.addEqualityGroup(reference, (Object[]) null));
7772
}
7873

7974
/**
@@ -195,21 +190,14 @@ public void testInvalidHashCode() {
195190

196191
public void testNullEqualityGroup() {
197192
EqualsTester tester = new EqualsTester();
198-
try {
199-
tester.addEqualityGroup((Object[]) null);
200-
fail();
201-
} catch (NullPointerException e) {
202-
}
193+
assertThrows(NullPointerException.class, () -> tester.addEqualityGroup((Object[]) null));
203194
}
204195

205196
public void testNullObjectInEqualityGroup() {
206197
EqualsTester tester = new EqualsTester();
207-
try {
208-
tester.addEqualityGroup(1, null, 3);
209-
fail();
210-
} catch (NullPointerException e) {
211-
assertErrorMessage(e, "at index 1");
212-
}
198+
NullPointerException e =
199+
assertThrows(NullPointerException.class, () -> tester.addEqualityGroup(1, null, 3));
200+
assertErrorMessage(e, "at index 1");
213201
}
214202

215203
public void testSymmetryBroken() {
@@ -274,12 +262,12 @@ public void testEqualityGroups() {
274262
}
275263

276264
public void testEqualityBasedOnToString() {
277-
try {
278-
new EqualsTester().addEqualityGroup(new EqualsBasedOnToString("foo")).testEquals();
279-
fail();
280-
} catch (AssertionFailedError e) {
281-
assertTrue(e.getMessage().contains("toString representation"));
282-
}
265+
AssertionFailedError e =
266+
assertThrows(
267+
AssertionFailedError.class,
268+
() ->
269+
new EqualsTester().addEqualityGroup(new EqualsBasedOnToString("foo")).testEquals());
270+
assertThat(e).hasMessageThat().contains("toString representation");
283271
}
284272

285273
private static void assertErrorMessage(Throwable e, String message) {

android/guava-testlib/test/com/google/common/testing/EquivalenceTesterTest.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package com.google.common.testing;
1818

1919
import static com.google.common.base.Preconditions.checkState;
20+
import static com.google.common.testing.ReflectionFreeAssertThrows.assertThrows;
2021
import static com.google.common.truth.Truth.assertThat;
2122

2223
import com.google.common.annotations.GwtCompatible;
@@ -46,11 +47,7 @@ public void setUp() throws Exception {
4647

4748
/** Test null reference yields error */
4849
public void testOf_nullPointerException() {
49-
try {
50-
EquivalenceTester.of(null);
51-
fail("Should fail on null reference");
52-
} catch (NullPointerException expected) {
53-
}
50+
assertThrows(NullPointerException.class, () -> EquivalenceTester.of(null));
5451
}
5552

5653
public void testTest_noData() {

android/guava-testlib/test/com/google/common/testing/FakeTickerTest.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
package com.google.common.testing;
1818

19+
import static com.google.common.testing.ReflectionFreeAssertThrows.assertThrows;
20+
1921
import com.google.common.annotations.GwtCompatible;
2022
import com.google.common.annotations.GwtIncompatible;
2123
import java.time.Duration;
@@ -108,11 +110,9 @@ public void testAutoIncrementStep_resetToZero() {
108110

109111
public void testAutoIncrement_negative() {
110112
FakeTicker ticker = new FakeTicker();
111-
try {
112-
ticker.setAutoIncrementStep(-1, TimeUnit.NANOSECONDS);
113-
fail("Expected IllegalArgumentException");
114-
} catch (IllegalArgumentException expected) {
115-
}
113+
assertThrows(
114+
IllegalArgumentException.class,
115+
() -> ticker.setAutoIncrementStep(-1, TimeUnit.NANOSECONDS));
116116
}
117117

118118
@GwtIncompatible // concurrency
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
/*
2+
* Copyright (C) 2024 The Guava Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
package com.google.common.testing;
16+
17+
import static com.google.common.base.Preconditions.checkNotNull;
18+
19+
import com.google.common.annotations.GwtCompatible;
20+
import com.google.common.annotations.GwtIncompatible;
21+
import com.google.common.annotations.J2ktIncompatible;
22+
import com.google.common.base.Predicate;
23+
import com.google.common.base.VerifyException;
24+
import com.google.common.collect.ImmutableMap;
25+
import com.google.common.util.concurrent.ExecutionError;
26+
import com.google.common.util.concurrent.UncheckedExecutionException;
27+
import com.google.errorprone.annotations.CanIgnoreReturnValue;
28+
import java.lang.reflect.InvocationTargetException;
29+
import java.nio.charset.UnsupportedCharsetException;
30+
import java.util.ConcurrentModificationException;
31+
import java.util.NoSuchElementException;
32+
import java.util.concurrent.CancellationException;
33+
import java.util.concurrent.ExecutionException;
34+
import java.util.concurrent.TimeoutException;
35+
import junit.framework.AssertionFailedError;
36+
import org.checkerframework.checker.nullness.qual.Nullable;
37+
38+
/** Replacements for JUnit's {@code assertThrows} that work under GWT/J2CL. */
39+
@GwtCompatible(emulated = true)
40+
@ElementTypesAreNonnullByDefault
41+
final class ReflectionFreeAssertThrows {
42+
interface ThrowingRunnable {
43+
void run() throws Throwable;
44+
}
45+
46+
interface ThrowingSupplier {
47+
@Nullable Object get() throws Throwable;
48+
}
49+
50+
@CanIgnoreReturnValue
51+
static <T extends Throwable> T assertThrows(
52+
Class<T> expectedThrowable, ThrowingSupplier supplier) {
53+
return doAssertThrows(expectedThrowable, supplier, /* userPassedSupplier= */ true);
54+
}
55+
56+
@CanIgnoreReturnValue
57+
static <T extends Throwable> T assertThrows(
58+
Class<T> expectedThrowable, ThrowingRunnable runnable) {
59+
return doAssertThrows(
60+
expectedThrowable,
61+
() -> {
62+
runnable.run();
63+
return null;
64+
},
65+
/* userPassedSupplier= */ false);
66+
}
67+
68+
private static <T extends Throwable> T doAssertThrows(
69+
Class<T> expectedThrowable, ThrowingSupplier supplier, boolean userPassedSupplier) {
70+
checkNotNull(expectedThrowable);
71+
checkNotNull(supplier);
72+
Predicate<Throwable> predicate = INSTANCE_OF.get(expectedThrowable);
73+
if (predicate == null) {
74+
throw new IllegalArgumentException(
75+
expectedThrowable
76+
+ " is not yet supported by ReflectionFreeAssertThrows. Add an entry for it in the"
77+
+ " map in that class.");
78+
}
79+
Object result;
80+
try {
81+
result = supplier.get();
82+
} catch (Throwable t) {
83+
if (predicate.apply(t)) {
84+
// We are careful to set up INSTANCE_OF to match each Predicate to its target Class.
85+
@SuppressWarnings("unchecked")
86+
T caught = (T) t;
87+
return caught;
88+
}
89+
throw new AssertionError(
90+
"expected to throw " + expectedThrowable.getSimpleName() + " but threw " + t, t);
91+
}
92+
if (userPassedSupplier) {
93+
throw new AssertionError(
94+
"expected to throw "
95+
+ expectedThrowable.getSimpleName()
96+
+ " but returned result: "
97+
+ result);
98+
} else {
99+
throw new AssertionError("expected to throw " + expectedThrowable.getSimpleName());
100+
}
101+
}
102+
103+
private enum PlatformSpecificExceptionBatch {
104+
PLATFORM {
105+
@GwtIncompatible
106+
@J2ktIncompatible
107+
@Override
108+
// returns the types available in "normal" environments
109+
ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> exceptions() {
110+
return ImmutableMap.of(
111+
InvocationTargetException.class,
112+
e -> e instanceof InvocationTargetException,
113+
StackOverflowError.class,
114+
e -> e instanceof StackOverflowError);
115+
}
116+
};
117+
118+
// used under GWT, etc., since the override of this method does not exist there
119+
ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> exceptions() {
120+
return ImmutableMap.of();
121+
}
122+
}
123+
124+
private static final ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> INSTANCE_OF =
125+
ImmutableMap.<Class<? extends Throwable>, Predicate<Throwable>>builder()
126+
.put(ArithmeticException.class, e -> e instanceof ArithmeticException)
127+
.put(
128+
ArrayIndexOutOfBoundsException.class,
129+
e -> e instanceof ArrayIndexOutOfBoundsException)
130+
.put(ArrayStoreException.class, e -> e instanceof ArrayStoreException)
131+
.put(AssertionFailedError.class, e -> e instanceof AssertionFailedError)
132+
.put(CancellationException.class, e -> e instanceof CancellationException)
133+
.put(ClassCastException.class, e -> e instanceof ClassCastException)
134+
.put(
135+
ConcurrentModificationException.class,
136+
e -> e instanceof ConcurrentModificationException)
137+
.put(ExecutionError.class, e -> e instanceof ExecutionError)
138+
.put(ExecutionException.class, e -> e instanceof ExecutionException)
139+
.put(IllegalArgumentException.class, e -> e instanceof IllegalArgumentException)
140+
.put(IllegalStateException.class, e -> e instanceof IllegalStateException)
141+
.put(IndexOutOfBoundsException.class, e -> e instanceof IndexOutOfBoundsException)
142+
.put(NoSuchElementException.class, e -> e instanceof NoSuchElementException)
143+
.put(NullPointerException.class, e -> e instanceof NullPointerException)
144+
.put(NumberFormatException.class, e -> e instanceof NumberFormatException)
145+
.put(RuntimeException.class, e -> e instanceof RuntimeException)
146+
.put(TimeoutException.class, e -> e instanceof TimeoutException)
147+
.put(UncheckedExecutionException.class, e -> e instanceof UncheckedExecutionException)
148+
.put(UnsupportedCharsetException.class, e -> e instanceof UnsupportedCharsetException)
149+
.put(UnsupportedOperationException.class, e -> e instanceof UnsupportedOperationException)
150+
.put(VerifyException.class, e -> e instanceof VerifyException)
151+
.putAll(PlatformSpecificExceptionBatch.PLATFORM.exceptions())
152+
.buildOrThrow();
153+
154+
private ReflectionFreeAssertThrows() {}
155+
}

0 commit comments

Comments
 (0)