diff options
Diffstat (limited to 'android/guava-tests/test/com/google/common/util')
30 files changed, 610 insertions, 1000 deletions
diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractChainedListenableFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractChainedListenableFutureTest.java index 85c4e14a5..d0d8e89c8 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractChainedListenableFutureTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractChainedListenableFutureTest.java @@ -17,6 +17,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.util.concurrent.testing.MockFutureListener; import java.util.concurrent.TimeUnit; @@ -49,11 +50,7 @@ public abstract class AbstractChainedListenableFutureTest<T> extends TestCase { public void testFutureGetBeforeCallback() throws Exception { // Verify that get throws a timeout exception before the callback is called. - try { - resultFuture.get(1L, TimeUnit.MILLISECONDS); - fail("The data is not yet ready, so a TimeoutException is expected"); - } catch (TimeoutException expected) { - } + assertThrows(TimeoutException.class, () -> resultFuture.get(1L, TimeUnit.MILLISECONDS)); } public void testFutureGetThrowsWrappedException() throws Exception { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractClosingFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractClosingFutureTest.java index 8f0fde236..1afeff403 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractClosingFutureTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractClosingFutureTest.java @@ -30,6 +30,7 @@ import static com.google.common.util.concurrent.Uninterruptibles.getUninterrupti import static java.util.Arrays.asList; import static java.util.concurrent.Executors.newSingleThreadExecutor; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; @@ -722,11 +723,7 @@ public abstract class AbstractClosingFutureTest extends TestCase { waitUntilClosed(closingFuture); assertStillOpen(closeable2); assertClosed(closeable1); - try { - capturedPeeker.get().getDone(input1); - fail("Peeker should not be able to peek except during call."); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> capturedPeeker.get().getDone(input1)); } public void testWhenAllComplete_call_cancelledPipeline() throws Exception { @@ -808,11 +805,7 @@ public abstract class AbstractClosingFutureTest extends TestCase { assertThat(getFinalValue(closingFuture)).isSameInstanceAs(closeable2); waitUntilClosed(closingFuture); assertClosed(closeable1, closeable2); - try { - capturedPeeker.get().getDone(input1); - fail("Peeker should not be able to peek except during call."); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> capturedPeeker.get().getDone(input1)); } public void testWhenAllComplete_callAsync_cancelledPipeline() throws Exception { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractExecutionThreadServiceTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractExecutionThreadServiceTest.java index 9b3f0f867..ad2a676c3 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractExecutionThreadServiceTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractExecutionThreadServiceTest.java @@ -17,6 +17,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.testing.TearDown; import com.google.common.testing.TearDownStack; @@ -175,12 +176,9 @@ public class AbstractExecutionThreadServiceTest extends TestCase { assertFalse(service.startUpCalled); service.startAsync(); - try { - service.awaitRunning(); - fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasCauseThat().hasMessageThat().isEqualTo("kaboom!"); - } + IllegalStateException expected = + assertThrows(IllegalStateException.class, () -> service.awaitRunning()); + assertThat(expected).hasCauseThat().hasMessageThat().isEqualTo("kaboom!"); executionThread.join(); assertTrue(service.startUpCalled); @@ -212,14 +210,11 @@ public class AbstractExecutionThreadServiceTest extends TestCase { ThrowOnRunService service = new ThrowOnRunService(); service.startAsync(); - try { - service.awaitTerminated(); - fail(); - } catch (IllegalStateException expected) { - executionThread.join(); - assertThat(expected).hasCauseThat().isEqualTo(service.failureCause()); - assertThat(expected).hasCauseThat().hasMessageThat().isEqualTo("kaboom!"); - } + IllegalStateException expected = + assertThrows(IllegalStateException.class, () -> service.awaitTerminated()); + executionThread.join(); + assertThat(expected).hasCauseThat().isEqualTo(service.failureCause()); + assertThat(expected).hasCauseThat().hasMessageThat().isEqualTo("kaboom!"); assertTrue(service.shutDownCalled); assertEquals(Service.State.FAILED, service.state()); } @@ -229,15 +224,11 @@ public class AbstractExecutionThreadServiceTest extends TestCase { service.throwOnShutDown = true; service.startAsync(); - try { - service.awaitTerminated(); - fail(); - } catch (IllegalStateException expected) { - executionThread.join(); - assertThat(expected).hasCauseThat().isEqualTo(service.failureCause()); - assertThat(expected).hasCauseThat().hasMessageThat().isEqualTo("kaboom!"); - } - + IllegalStateException expected = + assertThrows(IllegalStateException.class, () -> service.awaitTerminated()); + executionThread.join(); + assertThat(expected).hasCauseThat().isEqualTo(service.failureCause()); + assertThat(expected).hasCauseThat().hasMessageThat().isEqualTo("kaboom!"); assertTrue(service.shutDownCalled); assertEquals(Service.State.FAILED, service.state()); } @@ -303,12 +294,11 @@ public class AbstractExecutionThreadServiceTest extends TestCase { public void testServiceTimeoutOnStartUp() throws Exception { TimeoutOnStartUp service = new TimeoutOnStartUp(); - try { - service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS); - fail(); - } catch (TimeoutException e) { - assertThat(e.getMessage()).contains(Service.State.STARTING.toString()); - } + TimeoutException e = + assertThrows( + TimeoutException.class, + () -> service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS)); + assertThat(e.getMessage()).contains(Service.State.STARTING.toString()); } private class TimeoutOnStartUp extends AbstractExecutionThreadService { @@ -377,14 +367,13 @@ public class AbstractExecutionThreadServiceTest extends TestCase { return "Foo"; } }; - try { - service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS); - fail("Expected timeout"); - } catch (TimeoutException e) { - assertThat(e) - .hasMessageThat() - .isEqualTo("Timed out waiting for Foo [STARTING] to reach the RUNNING state."); - } + TimeoutException e = + assertThrows( + TimeoutException.class, + () -> service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS)); + assertThat(e) + .hasMessageThat() + .isEqualTo("Timed out waiting for Foo [STARTING] to reach the RUNNING state."); } private class FakeService extends AbstractExecutionThreadService implements TearDown { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureCancellationCauseTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureCancellationCauseTest.java index 9aee78029..d00f95f31 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureCancellationCauseTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureCancellationCauseTest.java @@ -17,6 +17,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.lang.reflect.Method; import java.net.URLClassLoader; @@ -89,12 +90,8 @@ public class AbstractFutureCancellationCauseTest extends TestCase { assertTrue(future.isCancelled()); assertTrue(future.isDone()); assertNull(tryInternalFastPathGetFailure(future)); - try { - future.get(); - fail("Expected CancellationException"); - } catch (CancellationException e) { - assertNotNull(e.getCause()); - } + CancellationException e = assertThrows(CancellationException.class, () -> future.get()); + assertNotNull(e.getCause()); } public void testCancel_notDoneInterrupt() throws Exception { @@ -103,12 +100,8 @@ public class AbstractFutureCancellationCauseTest extends TestCase { assertTrue(future.isCancelled()); assertTrue(future.isDone()); assertNull(tryInternalFastPathGetFailure(future)); - try { - future.get(); - fail("Expected CancellationException"); - } catch (CancellationException e) { - assertNotNull(e.getCause()); - } + CancellationException e = assertThrows(CancellationException.class, () -> future.get()); + assertNotNull(e.getCause()); } public void testSetFuture_misbehavingFutureDoesNotThrow() throws Exception { @@ -151,13 +144,9 @@ public class AbstractFutureCancellationCauseTest extends TestCase { "setFuture", future.getClass().getClassLoader().loadClass(ListenableFuture.class.getName())) .invoke(future, badFuture); - try { - future.get(); - fail(); - } catch (CancellationException expected) { - assertThat(expected).hasCauseThat().isInstanceOf(IllegalArgumentException.class); - assertThat(expected).hasCauseThat().hasMessageThat().contains(badFuture.toString()); - } + CancellationException expected = assertThrows(CancellationException.class, () -> future.get()); + assertThat(expected).hasCauseThat().isInstanceOf(IllegalArgumentException.class); + assertThat(expected).hasCauseThat().hasMessageThat().contains(badFuture.toString()); } private Future<?> newFutureInstance() throws Exception { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java index 89d92c8c4..6bf4c99d1 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractFutureTest.java @@ -20,6 +20,8 @@ import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_V import static com.google.common.base.StandardSystemProperty.OS_NAME; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; +import static com.google.common.util.concurrent.MoreExecutors.directExecutor; +import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.Iterables; @@ -97,13 +99,8 @@ public class AbstractFutureTest extends TestCase { assertTrue(future.isDone()); assertFalse(future.wasInterrupted()); assertFalse(future.interruptTaskWasCalled); - try { - future.get(); - fail("Expected CancellationException"); - } catch (CancellationException e) { - // See AbstractFutureCancellationCauseTest for how to set causes - assertThat(e).hasCauseThat().isNull(); - } + CancellationException e = assertThrows(CancellationException.class, () -> future.get()); + assertThat(e).hasCauseThat().isNull(); } public void testCancel_notDoneInterrupt() throws Exception { @@ -113,13 +110,8 @@ public class AbstractFutureTest extends TestCase { assertTrue(future.isDone()); assertTrue(future.wasInterrupted()); assertTrue(future.interruptTaskWasCalled); - try { - future.get(); - fail("Expected CancellationException"); - } catch (CancellationException e) { - // See AbstractFutureCancellationCauseTest for how to set causes - assertThat(e).hasCauseThat().isNull(); - } + CancellationException e = assertThrows(CancellationException.class, () -> future.get()); + assertThat(e).hasCauseThat().isNull(); } public void testCancel_done() throws Exception { @@ -156,12 +148,8 @@ public class AbstractFutureTest extends TestCase { AbstractFuture<String> normalFuture = new AbstractFuture<String>() {}; normalFuture.setFuture(evilFuture); assertTrue(normalFuture.isDone()); - try { - normalFuture.get(); - fail(); - } catch (ExecutionException e) { - assertThat(e).hasCauseThat().isSameInstanceAs(exception); - } + ExecutionException e = assertThrows(ExecutionException.class, () -> normalFuture.get()); + assertThat(e).hasCauseThat().isSameInstanceAs(exception); } public void testRemoveWaiter_interruption() throws Exception { @@ -266,13 +254,10 @@ public class AbstractFutureTest extends TestCase { assertThat(testFuture.toString()) .matches( "[^\\[]+\\[status=PENDING, info=\\[cause=\\[Because this test isn't done\\]\\]\\]"); - try { - testFuture.get(1, TimeUnit.NANOSECONDS); - fail(); - } catch (TimeoutException e) { - assertThat(e.getMessage()).contains("1 nanoseconds"); - assertThat(e.getMessage()).contains("Because this test isn't done"); - } + TimeoutException e = + assertThrows(TimeoutException.class, () -> testFuture.get(1, TimeUnit.NANOSECONDS)); + assertThat(e.getMessage()).contains("1 nanoseconds"); + assertThat(e.getMessage()).contains("Because this test isn't done"); } public void testToString_completesDuringToString() throws Exception { @@ -1072,6 +1057,25 @@ public class AbstractFutureTest extends TestCase { t.join(); } + public void testCatchesUndeclaredThrowableFromListener() { + AbstractFuture<String> f = new AbstractFuture<String>() {}; + f.set("foo"); + f.addListener(() -> sneakyThrow(new SomeCheckedException()), directExecutor()); + } + + private static final class SomeCheckedException extends Exception {} + + /** Throws an undeclared checked exception. */ + private static void sneakyThrow(Throwable t) { + class SneakyThrower<T extends Throwable> { + @SuppressWarnings("unchecked") // intentionally unsafe for test + void throwIt(Throwable t) throws T { + throw (T) t; + } + } + new SneakyThrower<Error>().throwIt(t); + } + public void testTrustedGetFailure_Completed() { SettableFuture<String> future = SettableFuture.create(); future.set("261"); @@ -1171,12 +1175,8 @@ public class AbstractFutureTest extends TestCase { SettableFuture<String> normalFuture = SettableFuture.create(); normalFuture.setFuture(new FailFuture(exception)); assertTrue(normalFuture.isDone()); - try { - normalFuture.get(); - fail(); - } catch (ExecutionException e) { - assertSame(exception, e.getCause()); - } + ExecutionException e = assertThrows(ExecutionException.class, () -> normalFuture.get()); + assertSame(exception, e.getCause()); } private static void awaitUnchecked(final CyclicBarrier barrier) { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java index 0444c31be..6d4b9c9d4 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractIdleServiceTest.java @@ -18,6 +18,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; +import static org.junit.Assert.assertThrows; import com.google.common.collect.Lists; import java.util.List; @@ -53,12 +54,9 @@ public class AbstractIdleServiceTest extends TestCase { } }; assertEquals(0, service.startUpCalled); - try { - service.startAsync().awaitRunning(); - fail(); - } catch (RuntimeException e) { - assertThat(e).hasCauseThat().isSameInstanceAs(exception); - } + RuntimeException e = + assertThrows(RuntimeException.class, () -> service.startAsync().awaitRunning()); + assertThat(e).hasCauseThat().isSameInstanceAs(exception); assertEquals(1, service.startUpCalled); assertEquals(Service.State.FAILED, service.state()); assertThat(service.transitionStates).containsExactly(Service.State.STARTING); @@ -100,12 +98,9 @@ public class AbstractIdleServiceTest extends TestCase { service.startAsync().awaitRunning(); assertEquals(1, service.startUpCalled); assertEquals(0, service.shutDownCalled); - try { - service.stopAsync().awaitTerminated(); - fail(); - } catch (RuntimeException e) { - assertThat(e).hasCauseThat().isSameInstanceAs(exception); - } + RuntimeException e = + assertThrows(RuntimeException.class, () -> service.stopAsync().awaitTerminated()); + assertThat(e).hasCauseThat().isSameInstanceAs(exception); assertEquals(1, service.startUpCalled); assertEquals(1, service.shutDownCalled); assertEquals(Service.State.FAILED, service.state()); @@ -140,14 +135,13 @@ public class AbstractIdleServiceTest extends TestCase { return "Foo"; } }; - try { - service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS); - fail("Expected timeout"); - } catch (TimeoutException e) { - assertThat(e) - .hasMessageThat() - .isEqualTo("Timed out waiting for Foo [STARTING] to reach the RUNNING state."); - } + TimeoutException e = + assertThrows( + TimeoutException.class, + () -> service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS)); + assertThat(e) + .hasMessageThat() + .isEqualTo("Timed out waiting for Foo [STARTING] to reach the RUNNING state."); } private static class TestService extends AbstractIdleService { @@ -206,12 +200,9 @@ public class AbstractIdleServiceTest extends TestCase { throw exception; } }; - try { - service.startAsync().awaitRunning(); - fail(); - } catch (RuntimeException e) { - assertThat(e).hasCauseThat().isSameInstanceAs(exception); - } + RuntimeException e = + assertThrows(RuntimeException.class, () -> service.startAsync().awaitRunning()); + assertThat(e).hasCauseThat().isSameInstanceAs(exception); assertEquals(Service.State.FAILED, service.state()); } @@ -225,12 +216,9 @@ public class AbstractIdleServiceTest extends TestCase { } }; service.startAsync().awaitRunning(); - try { - service.stopAsync().awaitTerminated(); - fail(); - } catch (RuntimeException e) { - assertThat(e).hasCauseThat().isSameInstanceAs(exception); - } + RuntimeException e = + assertThrows(RuntimeException.class, () -> service.stopAsync().awaitTerminated()); + assertThat(e).hasCauseThat().isSameInstanceAs(exception); assertEquals(Service.State.FAILED, service.state()); } } diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java index f7266b274..b3c606986 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractScheduledServiceTest.java @@ -22,6 +22,7 @@ import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.util.concurrent.AbstractScheduledService.Cancellable; import com.google.common.util.concurrent.AbstractScheduledService.Scheduler; @@ -97,11 +98,7 @@ public class AbstractScheduledServiceTest extends TestCase { service.startAsync().awaitRunning(); service.runFirstBarrier.await(); service.runSecondBarrier.await(); - try { - future.get(); - fail(); - } catch (CancellationException expected) { - } + assertThrows(CancellationException.class, () -> future.get()); // An execution exception holds a runtime exception (from throwables.propagate) that holds our // original exception. assertEquals(service.runException, service.failureCause()); @@ -111,12 +108,9 @@ public class AbstractScheduledServiceTest extends TestCase { public void testFailOnExceptionFromStartUp() { TestService service = new TestService(); service.startUpException = new Exception(); - try { - service.startAsync().awaitRunning(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasCauseThat().isEqualTo(service.startUpException); - } + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.startAsync().awaitRunning()); + assertThat(e).hasCauseThat().isEqualTo(service.startUpException); assertEquals(0, service.numberOfTimesRunCalled.get()); assertEquals(Service.State.FAILED, service.state()); } @@ -154,12 +148,9 @@ public class AbstractScheduledServiceTest extends TestCase { service.runFirstBarrier.await(); service.stopAsync(); service.runSecondBarrier.await(); - try { - service.awaitTerminated(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasCauseThat().isEqualTo(service.shutDownException); - } + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.awaitTerminated()); + assertThat(e).hasCauseThat().isEqualTo(service.shutDownException); assertEquals(Service.State.FAILED, service.state()); } @@ -246,11 +237,7 @@ public class AbstractScheduledServiceTest extends TestCase { } }; - try { - service.startAsync().awaitRunning(); - fail("Expected service to fail during startup"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> service.startAsync().awaitRunning()); assertTrue(executor.get().awaitTermination(100, MILLISECONDS)); } @@ -295,14 +282,12 @@ public class AbstractScheduledServiceTest extends TestCase { return "Foo"; } }; - try { - service.startAsync().awaitRunning(1, MILLISECONDS); - fail("Expected timeout"); - } catch (TimeoutException e) { - assertThat(e) - .hasMessageThat() - .isEqualTo("Timed out waiting for Foo [STARTING] to reach the RUNNING state."); - } + TimeoutException e = + assertThrows( + TimeoutException.class, () -> service.startAsync().awaitRunning(1, MILLISECONDS)); + assertThat(e) + .hasMessageThat() + .isEqualTo("Timed out waiting for Foo [STARTING] to reach the RUNNING state."); } private class TestService extends AbstractScheduledService { @@ -453,11 +438,7 @@ public class AbstractScheduledServiceTest extends TestCase { } }; service.startAsync().awaitRunning(); - try { - service.firstBarrier.await(5, SECONDS); - fail(); - } catch (TimeoutException expected) { - } + assertThrows(TimeoutException.class, () -> service.firstBarrier.await(5, SECONDS)); assertEquals(0, service.numIterations.get()); service.stopAsync(); service.awaitTerminated(); @@ -478,11 +459,7 @@ public class AbstractScheduledServiceTest extends TestCase { } }; service.startAsync().awaitRunning(); - try { - service.firstBarrier.await(5, SECONDS); - fail(); - } catch (TimeoutException expected) { - } + assertThrows(TimeoutException.class, () -> service.firstBarrier.await(5, SECONDS)); assertEquals(0, service.numIterations.get()); service.stopAsync(); service.awaitTerminated(); @@ -639,12 +616,10 @@ public class AbstractScheduledServiceTest extends TestCase { service.secondBarrier.await(); } Thread.sleep(1000); - try { - service.stopAsync().awaitTerminated(100, SECONDS); - fail(); - } catch (IllegalStateException e) { - assertEquals(State.FAILED, service.state()); - } + IllegalStateException e = + assertThrows( + IllegalStateException.class, () -> service.stopAsync().awaitTerminated(100, SECONDS)); + assertEquals(State.FAILED, service.state()); } private static class TestFailingCustomScheduledService extends AbstractScheduledService { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java index 5f4210621..e4d310331 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AbstractServiceTest.java @@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static java.lang.Thread.currentThread; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; @@ -449,12 +450,9 @@ public class AbstractServiceTest extends TestCase { service.notifyFailed(new Exception("1")); service.notifyFailed(new Exception("2")); assertThat(service.failureCause()).hasMessageThat().isEqualTo("1"); - try { - service.awaitRunning(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("1"); - } + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.awaitRunning()); + assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("1"); } private class ThreadedService extends AbstractService { @@ -531,11 +529,7 @@ public class AbstractServiceTest extends TestCase { service.stopAsync(); assertEquals(State.TERMINATED, service.state()); - try { - service.startAsync(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> service.startAsync()); assertEquals(State.TERMINATED, Iterables.getOnlyElement(listener.getStateHistory())); } @@ -543,13 +537,10 @@ public class AbstractServiceTest extends TestCase { StartFailingService service = new StartFailingService(); RecordingListener listener = RecordingListener.record(service); - try { - service.startAsync().awaitRunning(); - fail(); - } catch (IllegalStateException e) { - assertEquals(EXCEPTION, service.failureCause()); - assertThat(e).hasCauseThat().isEqualTo(EXCEPTION); - } + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.startAsync().awaitRunning()); + assertEquals(EXCEPTION, service.failureCause()); + assertThat(e).hasCauseThat().isEqualTo(EXCEPTION); assertEquals(ImmutableList.of(State.STARTING, State.FAILED), listener.getStateHistory()); } @@ -558,13 +549,10 @@ public class AbstractServiceTest extends TestCase { RecordingListener listener = RecordingListener.record(service); service.startAsync().awaitRunning(); - try { - service.stopAsync().awaitTerminated(); - fail(); - } catch (IllegalStateException e) { - assertEquals(EXCEPTION, service.failureCause()); - assertThat(e).hasCauseThat().isEqualTo(EXCEPTION); - } + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.stopAsync().awaitTerminated()); + assertEquals(EXCEPTION, service.failureCause()); + assertThat(e).hasCauseThat().isEqualTo(EXCEPTION); assertEquals( ImmutableList.of(State.STARTING, State.RUNNING, State.STOPPING, State.FAILED), listener.getStateHistory()); @@ -575,13 +563,10 @@ public class AbstractServiceTest extends TestCase { RecordingListener listener = RecordingListener.record(service); service.startAsync(); - try { - service.awaitRunning(); - fail(); - } catch (IllegalStateException e) { - assertEquals(EXCEPTION, service.failureCause()); - assertThat(e).hasCauseThat().isEqualTo(EXCEPTION); - } + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.awaitRunning()); + assertEquals(EXCEPTION, service.failureCause()); + assertThat(e).hasCauseThat().isEqualTo(EXCEPTION); assertEquals( ImmutableList.of(State.STARTING, State.RUNNING, State.FAILED), listener.getStateHistory()); } @@ -590,13 +575,10 @@ public class AbstractServiceTest extends TestCase { StartThrowingService service = new StartThrowingService(); RecordingListener listener = RecordingListener.record(service); - try { - service.startAsync().awaitRunning(); - fail(); - } catch (IllegalStateException e) { - assertEquals(service.exception, service.failureCause()); - assertThat(e).hasCauseThat().isEqualTo(service.exception); - } + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.startAsync().awaitRunning()); + assertEquals(service.exception, service.failureCause()); + assertThat(e).hasCauseThat().isEqualTo(service.exception); assertEquals(ImmutableList.of(State.STARTING, State.FAILED), listener.getStateHistory()); } @@ -605,13 +587,10 @@ public class AbstractServiceTest extends TestCase { RecordingListener listener = RecordingListener.record(service); service.startAsync().awaitRunning(); - try { - service.stopAsync().awaitTerminated(); - fail(); - } catch (IllegalStateException e) { - assertEquals(service.exception, service.failureCause()); - assertThat(e).hasCauseThat().isEqualTo(service.exception); - } + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.stopAsync().awaitTerminated()); + assertEquals(service.exception, service.failureCause()); + assertThat(e).hasCauseThat().isEqualTo(service.exception); assertEquals( ImmutableList.of(State.STARTING, State.RUNNING, State.STOPPING, State.FAILED), listener.getStateHistory()); @@ -622,37 +601,23 @@ public class AbstractServiceTest extends TestCase { RecordingListener listener = RecordingListener.record(service); service.startAsync(); - try { - service.awaitTerminated(); - fail(); - } catch (IllegalStateException e) { - assertEquals(service.exception, service.failureCause()); - assertThat(e).hasCauseThat().isEqualTo(service.exception); - } + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.awaitTerminated()); + assertEquals(service.exception, service.failureCause()); + assertThat(e).hasCauseThat().isEqualTo(service.exception); assertEquals( ImmutableList.of(State.STARTING, State.RUNNING, State.FAILED), listener.getStateHistory()); } public void testFailureCause_throwsIfNotFailed() { StopFailingService service = new StopFailingService(); - try { - service.failureCause(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> service.failureCause()); service.startAsync().awaitRunning(); - try { - service.failureCause(); - fail(); - } catch (IllegalStateException expected) { - } - try { - service.stopAsync().awaitTerminated(); - fail(); - } catch (IllegalStateException e) { - assertEquals(EXCEPTION, service.failureCause()); - assertThat(e).hasCauseThat().isEqualTo(EXCEPTION); - } + assertThrows(IllegalStateException.class, () -> service.failureCause()); + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> service.stopAsync().awaitTerminated()); + assertEquals(EXCEPTION, service.failureCause()); + assertThat(e).hasCauseThat().isEqualTo(EXCEPTION); } public void testAddListenerAfterFailureDoesntCauseDeadlock() throws InterruptedException { @@ -912,40 +877,24 @@ public class AbstractServiceTest extends TestCase { public void testNotifyStartedWhenNotStarting() { AbstractService service = new DefaultService(); - try { - service.notifyStarted(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> service.notifyStarted()); } public void testNotifyStoppedWhenNotRunning() { AbstractService service = new DefaultService(); - try { - service.notifyStopped(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> service.notifyStopped()); } public void testNotifyFailedWhenNotStarted() { AbstractService service = new DefaultService(); - try { - service.notifyFailed(new Exception()); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> service.notifyFailed(new Exception())); } public void testNotifyFailedWhenTerminated() { NoOpService service = new NoOpService(); service.startAsync().awaitRunning(); service.stopAsync().awaitTerminated(); - try { - service.notifyFailed(new Exception()); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> service.notifyFailed(new Exception())); } private static class DefaultService extends AbstractService { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AtomicDoubleArrayTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AtomicDoubleArrayTest.java index 5bb1cb74e..4220d873f 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AtomicDoubleArrayTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AtomicDoubleArrayTest.java @@ -13,6 +13,8 @@ package com.google.common.util.concurrent; +import static org.junit.Assert.assertThrows; + import java.util.Arrays; /** Unit test for {@link AtomicDoubleArray}. */ @@ -59,11 +61,7 @@ public class AtomicDoubleArrayTest extends JSR166TestCase { /** constructor with null array throws NPE */ public void testConstructor2NPE() { double[] a = null; - try { - new AtomicDoubleArray(a); - fail(); - } catch (NullPointerException success) { - } + assertThrows(NullPointerException.class, () -> new AtomicDoubleArray(a)); } /** constructor with array is of same size and has all elements */ @@ -79,63 +77,27 @@ public class AtomicDoubleArrayTest extends JSR166TestCase { public void testConstructorEmptyArray() { AtomicDoubleArray aa = new AtomicDoubleArray(new double[0]); assertEquals(0, aa.length()); - try { - aa.get(0); - fail(); - } catch (IndexOutOfBoundsException success) { - } + assertThrows(IndexOutOfBoundsException.class, () -> aa.get(0)); } /** constructor with length zero has size 0 and contains no elements */ public void testConstructorZeroLength() { AtomicDoubleArray aa = new AtomicDoubleArray(0); assertEquals(0, aa.length()); - try { - aa.get(0); - fail(); - } catch (IndexOutOfBoundsException success) { - } + assertThrows(IndexOutOfBoundsException.class, () -> aa.get(0)); } /** get and set for out of bound indices throw IndexOutOfBoundsException */ public void testIndexing() { AtomicDoubleArray aa = new AtomicDoubleArray(SIZE); for (int index : new int[] {-1, SIZE}) { - try { - aa.get(index); - fail(); - } catch (IndexOutOfBoundsException success) { - } - try { - aa.set(index, 1.0); - fail(); - } catch (IndexOutOfBoundsException success) { - } - try { - aa.lazySet(index, 1.0); - fail(); - } catch (IndexOutOfBoundsException success) { - } - try { - aa.compareAndSet(index, 1.0, 2.0); - fail(); - } catch (IndexOutOfBoundsException success) { - } - try { - aa.weakCompareAndSet(index, 1.0, 2.0); - fail(); - } catch (IndexOutOfBoundsException success) { - } - try { - aa.getAndAdd(index, 1.0); - fail(); - } catch (IndexOutOfBoundsException success) { - } - try { - aa.addAndGet(index, 1.0); - fail(); - } catch (IndexOutOfBoundsException success) { - } + assertThrows(IndexOutOfBoundsException.class, () -> aa.get(index)); + assertThrows(IndexOutOfBoundsException.class, () -> aa.set(index, 1.0)); + assertThrows(IndexOutOfBoundsException.class, () -> aa.lazySet(index, 1.0)); + assertThrows(IndexOutOfBoundsException.class, () -> aa.compareAndSet(index, 1.0, 2.0)); + assertThrows(IndexOutOfBoundsException.class, () -> aa.weakCompareAndSet(index, 1.0, 2.0)); + assertThrows(IndexOutOfBoundsException.class, () -> aa.getAndAdd(index, 1.0)); + assertThrows(IndexOutOfBoundsException.class, () -> aa.addAndGet(index, 1.0)); } } diff --git a/android/guava-tests/test/com/google/common/util/concurrent/AtomicsTest.java b/android/guava-tests/test/com/google/common/util/concurrent/AtomicsTest.java index b903e6ce8..90f0f6f76 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/AtomicsTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/AtomicsTest.java @@ -16,6 +16,8 @@ package com.google.common.util.concurrent; +import static org.junit.Assert.assertThrows; + import com.google.common.testing.NullPointerTester; import java.util.concurrent.atomic.AtomicReferenceArray; import junit.framework.TestCase; @@ -44,19 +46,11 @@ public class AtomicsTest extends TestCase { for (int i = 0; i < length; ++i) { assertEquals(null, refArray.get(i)); } - try { - refArray.get(length); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> refArray.get(length)); } public void testNewReferenceArray_withNegativeLength() throws Exception { - try { - Atomics.newReferenceArray(-1); - fail(); - } catch (NegativeArraySizeException expected) { - } + assertThrows(NegativeArraySizeException.class, () -> Atomics.newReferenceArray(-1)); } public void testNewReferenceArray_withStringArray() throws Exception { @@ -65,19 +59,11 @@ public class AtomicsTest extends TestCase { for (int i = 0; i < array.length; ++i) { assertEquals(array[i], refArray.get(i)); } - try { - refArray.get(array.length); - fail(); - } catch (IndexOutOfBoundsException expected) { - } + assertThrows(IndexOutOfBoundsException.class, () -> refArray.get(array.length)); } public void testNewReferenceArray_withNullArray() throws Exception { - try { - Atomics.newReferenceArray(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> Atomics.newReferenceArray(null)); } public void testNullPointers() { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ClosingFutureFinishToFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/ClosingFutureFinishToFutureTest.java index 79288eb2a..29ce341e1 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/ClosingFutureFinishToFutureTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/ClosingFutureFinishToFutureTest.java @@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly; +import static org.junit.Assert.assertThrows; import com.google.common.util.concurrent.ClosingFuture.ClosingCallable; import com.google.common.util.concurrent.ClosingFuture.DeferredCloser; @@ -39,11 +40,11 @@ public class ClosingFutureFinishToFutureTest extends AbstractClosingFutureTest { }, executor); FluentFuture<Closeable> unused = closingFuture.finishToFuture(); - try { - FluentFuture<Closeable> unused2 = closingFuture.finishToFuture(); - fail("should have thrown"); - } catch (IllegalStateException expected) { - } + assertThrows( + IllegalStateException.class, + () -> { + FluentFuture<Closeable> unused2 = closingFuture.finishToFuture(); + }); } public void testFinishToFuture_throwsAfterCallingFinishToValueAndCloser() throws Exception { @@ -57,11 +58,11 @@ public class ClosingFutureFinishToFutureTest extends AbstractClosingFutureTest { }, executor); closingFuture.finishToValueAndCloser(new NoOpValueAndCloserConsumer<>(), directExecutor()); - try { - FluentFuture<Closeable> unused = closingFuture.finishToFuture(); - fail("should have thrown"); - } catch (IllegalStateException expected) { - } + assertThrows( + IllegalStateException.class, + () -> { + FluentFuture<Closeable> unused = closingFuture.finishToFuture(); + }); } public void testFinishToFuture_preventsFurtherDerivation() { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ClosingFutureFinishToValueAndCloserTest.java b/android/guava-tests/test/com/google/common/util/concurrent/ClosingFutureFinishToValueAndCloserTest.java index ac3cf5569..c249eca34 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/ClosingFutureFinishToValueAndCloserTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/ClosingFutureFinishToValueAndCloserTest.java @@ -22,6 +22,7 @@ import static com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTe import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; import static java.util.concurrent.Executors.newSingleThreadExecutor; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.util.concurrent.ClosingFuture.ClosingCallable; import com.google.common.util.concurrent.ClosingFuture.DeferredCloser; @@ -61,12 +62,11 @@ public class ClosingFutureFinishToValueAndCloserTest extends AbstractClosingFutu executor); closingFuture.finishToValueAndCloser( new NoOpValueAndCloserConsumer<>(), finishToValueAndCloserExecutor); - try { - closingFuture.finishToValueAndCloser( - new NoOpValueAndCloserConsumer<>(), finishToValueAndCloserExecutor); - fail("should have thrown"); - } catch (IllegalStateException expected) { - } + assertThrows( + IllegalStateException.class, + () -> + closingFuture.finishToValueAndCloser( + new NoOpValueAndCloserConsumer<>(), finishToValueAndCloserExecutor)); } public void testFinishToValueAndCloser_throwsAfterCallingFinishToFuture() throws Exception { @@ -80,12 +80,11 @@ public class ClosingFutureFinishToValueAndCloserTest extends AbstractClosingFutu }, executor); FluentFuture<Closeable> unused = closingFuture.finishToFuture(); - try { - closingFuture.finishToValueAndCloser( - new NoOpValueAndCloserConsumer<>(), finishToValueAndCloserExecutor); - fail("should have thrown"); - } catch (IllegalStateException expected) { - } + assertThrows( + IllegalStateException.class, + () -> + closingFuture.finishToValueAndCloser( + new NoOpValueAndCloserConsumer<>(), finishToValueAndCloserExecutor)); } @Override diff --git a/android/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java b/android/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java index bf388b0ba..3e88ecb11 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/CycleDetectingLockFactoryTest.java @@ -17,6 +17,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.base.Joiner; import com.google.common.util.concurrent.CycleDetectingLockFactory.Policies; @@ -102,24 +103,15 @@ public class CycleDetectingLockFactoryTest extends TestCase { // The opposite order should fail (Policies.THROW). PotentialDeadlockException firstException = null; lockB.lock(); - try { - lockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "LockB -> LockA", "LockA -> LockB"); - firstException = expected; - } - + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> lockA.lock()); + checkMessage(expected, "LockB -> LockA", "LockA -> LockB"); + firstException = expected; // Second time should also fail, with a cached causal chain. - try { - lockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "LockB -> LockA", "LockA -> LockB"); - // The causal chain should be cached. - assertSame(firstException.getCause(), expected.getCause()); - } - + expected = assertThrows(PotentialDeadlockException.class, () -> lockA.lock()); + checkMessage(expected, "LockB -> LockA", "LockA -> LockB"); + // The causal chain should be cached. + assertSame(firstException.getCause(), expected.getCause()); // lockA should work after lockB is released. lockB.unlock(); lockA.lock(); @@ -139,12 +131,9 @@ public class CycleDetectingLockFactoryTest extends TestCase { lockB.unlock(); // lockC -> lockA should fail. - try { - lockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "LockC -> LockA", "LockB -> LockC", "LockA -> LockB"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> lockA.lock()); + checkMessage(expected, "LockC -> LockA", "LockB -> LockC", "LockA -> LockB"); } public void testReentrancy_noDeadlock() { @@ -163,29 +152,18 @@ public class CycleDetectingLockFactoryTest extends TestCase { public void testExplicitOrdering_violations() { lock3.lock(); - try { - lock2.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "MyOrder.THIRD -> MyOrder.SECOND"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> lock2.lock()); + checkMessage(expected, "MyOrder.THIRD -> MyOrder.SECOND"); - try { - lock1.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "MyOrder.THIRD -> MyOrder.FIRST"); - } + expected = assertThrows(PotentialDeadlockException.class, () -> lock1.lock()); + checkMessage(expected, "MyOrder.THIRD -> MyOrder.FIRST"); lock3.unlock(); lock2.lock(); - try { - lock1.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "MyOrder.SECOND -> MyOrder.FIRST"); - } + expected = assertThrows(PotentialDeadlockException.class, () -> lock1.lock()); + checkMessage(expected, "MyOrder.SECOND -> MyOrder.FIRST"); } public void testDifferentOrderings_noViolations() { @@ -198,26 +176,18 @@ public class CycleDetectingLockFactoryTest extends TestCase { lock01.lock(); // OtherOrder, ordinal() == 1 lock3.unlock(); - try { - lock3.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage( - expected, "OtherOrder.FIRST -> MyOrder.THIRD", "MyOrder.THIRD -> OtherOrder.FIRST"); - } - + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> lock3.lock()); + checkMessage( + expected, "OtherOrder.FIRST -> MyOrder.THIRD", "MyOrder.THIRD -> OtherOrder.FIRST"); lockA.lock(); lock01.unlock(); lockB.lock(); lockA.unlock(); - try { - lock01.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage( - expected, "LockB -> OtherOrder.FIRST", "LockA -> LockB", "OtherOrder.FIRST -> LockA"); - } + expected = assertThrows(PotentialDeadlockException.class, () -> lock01.lock()); + checkMessage( + expected, "LockB -> OtherOrder.FIRST", "LockA -> LockB", "OtherOrder.FIRST -> LockA"); } public void testExplicitOrdering_cycleWithUnorderedLock() { @@ -226,16 +196,13 @@ public class CycleDetectingLockFactoryTest extends TestCase { myLock.lock(); lock03.unlock(); - try { - lock01.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage( - expected, - "MyLock -> OtherOrder.FIRST", - "OtherOrder.THIRD -> MyLock", - "OtherOrder.FIRST -> OtherOrder.THIRD"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> lock01.lock()); + checkMessage( + expected, + "MyLock -> OtherOrder.FIRST", + "OtherOrder.THIRD -> MyLock", + "OtherOrder.FIRST -> OtherOrder.THIRD"); } public void testExplicitOrdering_reentrantAcquisition() { @@ -261,11 +228,7 @@ public class CycleDetectingLockFactoryTest extends TestCase { Lock lockB = factory.newReentrantReadWriteLock(OtherOrder.FIRST).readLock(); lockA.lock(); - try { - lockB.lock(); - fail("Expected IllegalStateException"); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> lockB.lock()); lockA.unlock(); lockB.lock(); @@ -278,12 +241,9 @@ public class CycleDetectingLockFactoryTest extends TestCase { readLockA.unlock(); lockB.lock(); - try { - readLockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> readLockA.lock()); + checkMessage(expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB"); } public void testReadLock_transitive() { @@ -300,13 +260,10 @@ public class CycleDetectingLockFactoryTest extends TestCase { // readLockC -> readLockA readLockC.lock(); - try { - readLockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage( - expected, "ReadWriteC -> ReadWriteA", "LockB -> ReadWriteC", "ReadWriteA -> LockB"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> readLockA.lock()); + checkMessage( + expected, "ReadWriteC -> ReadWriteA", "LockB -> ReadWriteC", "ReadWriteA -> LockB"); } public void testWriteLock_threeLockDeadLock() { @@ -322,16 +279,13 @@ public class CycleDetectingLockFactoryTest extends TestCase { writeLockB.unlock(); // writeLockC -> writeLockA should fail. - try { - writeLockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage( - expected, - "ReadWriteC -> ReadWriteA", - "ReadWriteB -> ReadWriteC", - "ReadWriteA -> ReadWriteB"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> writeLockA.lock()); + checkMessage( + expected, + "ReadWriteC -> ReadWriteA", + "ReadWriteB -> ReadWriteC", + "ReadWriteA -> ReadWriteB"); } public void testWriteToReadLockDowngrading() { @@ -343,12 +297,9 @@ public class CycleDetectingLockFactoryTest extends TestCase { readLockA.unlock(); // lockB -> writeLockA should fail - try { - writeLockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> writeLockA.lock()); + checkMessage(expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB"); } public void testReadWriteLockDeadlock() { @@ -359,12 +310,9 @@ public class CycleDetectingLockFactoryTest extends TestCase { // lockB -> readLockA should fail. lockB.lock(); - try { - readLockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> readLockA.lock()); + checkMessage(expected, "LockB -> ReadWriteA", "ReadWriteA -> LockB"); } public void testReadWriteLockDeadlock_transitive() { @@ -381,12 +329,9 @@ public class CycleDetectingLockFactoryTest extends TestCase { // lockC -> writeLockA should fail. lockC.lock(); - try { - writeLockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "LockC -> ReadWriteA", "LockB -> LockC", "ReadWriteA -> LockB"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> writeLockA.lock()); + checkMessage(expected, "LockC -> ReadWriteA", "LockB -> LockC", "ReadWriteA -> LockB"); } public void testReadWriteLockDeadlock_treatedEquivalently() { @@ -397,12 +342,9 @@ public class CycleDetectingLockFactoryTest extends TestCase { // readLockB -> writeLockA should fail. readLockB.lock(); - try { - writeLockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "ReadWriteB -> ReadWriteA", "ReadWriteA -> ReadWriteB"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> writeLockA.lock()); + checkMessage(expected, "ReadWriteB -> ReadWriteA", "ReadWriteA -> ReadWriteB"); } public void testDifferentLockFactories() { @@ -417,12 +359,9 @@ public class CycleDetectingLockFactoryTest extends TestCase { // lockD -> lockA should fail even though lockD is from a different factory. lockD.lock(); - try { - lockA.lock(); - fail("Expected PotentialDeadlockException"); - } catch (PotentialDeadlockException expected) { - checkMessage(expected, "LockD -> LockA", "LockA -> LockD"); - } + PotentialDeadlockException expected = + assertThrows(PotentialDeadlockException.class, () -> lockA.lock()); + checkMessage(expected, "LockD -> LockA", "LockA -> LockD"); } public void testDifferentLockFactories_policyExecution() { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/FakeTimeLimiterTest.java b/android/guava-tests/test/com/google/common/util/concurrent/FakeTimeLimiterTest.java index a0e063469..4eb72e3b7 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/FakeTimeLimiterTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/FakeTimeLimiterTest.java @@ -17,6 +17,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; @@ -51,22 +52,24 @@ public class FakeTimeLimiterTest extends TestCase { public void testCallWithTimeout_wrapsCheckedException() throws Exception { Exception exception = new SampleCheckedException(); - try { - timeLimiter.callWithTimeout(callableThrowing(exception), DELAY_MS, TimeUnit.MILLISECONDS); - fail("Expected ExecutionException"); - } catch (ExecutionException e) { - assertThat(e.getCause()).isEqualTo(exception); - } + ExecutionException e = + assertThrows( + ExecutionException.class, + () -> + timeLimiter.callWithTimeout( + callableThrowing(exception), DELAY_MS, TimeUnit.MILLISECONDS)); + assertThat(e.getCause()).isEqualTo(exception); } public void testCallWithTimeout_wrapsUncheckedException() throws Exception { Exception exception = new RuntimeException("test"); - try { - timeLimiter.callWithTimeout(callableThrowing(exception), DELAY_MS, TimeUnit.MILLISECONDS); - fail("Expected UncheckedExecutionException"); - } catch (UncheckedExecutionException e) { - assertThat(e.getCause()).isEqualTo(exception); - } + UncheckedExecutionException e = + assertThrows( + UncheckedExecutionException.class, + () -> + timeLimiter.callWithTimeout( + callableThrowing(exception), DELAY_MS, TimeUnit.MILLISECONDS)); + assertThat(e.getCause()).isEqualTo(exception); } public void testCallUninterruptiblyWithTimeout_propagatesReturnValue() throws Exception { @@ -83,23 +86,24 @@ public class FakeTimeLimiterTest extends TestCase { public void testRunWithTimeout_wrapsUncheckedException() throws Exception { RuntimeException exception = new RuntimeException("test"); - try { - timeLimiter.runWithTimeout(runnableThrowing(exception), DELAY_MS, TimeUnit.MILLISECONDS); - fail("Expected UncheckedExecutionException"); - } catch (UncheckedExecutionException e) { - assertThat(e.getCause()).isEqualTo(exception); - } + UncheckedExecutionException e = + assertThrows( + UncheckedExecutionException.class, + () -> + timeLimiter.runWithTimeout( + runnableThrowing(exception), DELAY_MS, TimeUnit.MILLISECONDS)); + assertThat(e.getCause()).isEqualTo(exception); } public void testRunUninterruptiblyWithTimeout_wrapsUncheckedException() throws Exception { RuntimeException exception = new RuntimeException("test"); - try { - timeLimiter.runUninterruptiblyWithTimeout( - runnableThrowing(exception), DELAY_MS, TimeUnit.MILLISECONDS); - fail("Expected UncheckedExecutionException"); - } catch (UncheckedExecutionException e) { - assertThat(e.getCause()).isEqualTo(exception); - } + UncheckedExecutionException e = + assertThrows( + UncheckedExecutionException.class, + () -> + timeLimiter.runUninterruptiblyWithTimeout( + runnableThrowing(exception), DELAY_MS, TimeUnit.MILLISECONDS)); + assertThat(e.getCause()).isEqualTo(exception); } public static <T> Callable<T> callableThrowing(final Exception exception) { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/FluentFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/FluentFutureTest.java index ab53f5383..48d5c8e5a 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/FluentFutureTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/FluentFutureTest.java @@ -23,6 +23,7 @@ import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @@ -138,12 +139,8 @@ public class FluentFutureTest extends TestCase { try { FluentFuture<?> f = FluentFuture.from(SettableFuture.create()).withTimeout(0, SECONDS, executor); - try { - f.get(); - fail(); - } catch (ExecutionException e) { - assertThat(e).hasCauseThat().isInstanceOf(TimeoutException.class); - } + ExecutionException e = assertThrows(ExecutionException.class, () -> f.get()); + assertThat(e).hasCauseThat().isInstanceOf(TimeoutException.class); } finally { executor.shutdown(); } diff --git a/android/guava-tests/test/com/google/common/util/concurrent/FuturesGetCheckedInputs.java b/android/guava-tests/test/com/google/common/util/concurrent/FuturesGetCheckedInputs.java index 27916d8a1..0ae248837 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/FuturesGetCheckedInputs.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/FuturesGetCheckedInputs.java @@ -18,6 +18,7 @@ import static com.google.common.util.concurrent.Futures.immediateFailedFuture; import com.google.common.annotations.GwtCompatible; import java.util.concurrent.Future; +import javax.annotation.CheckForNull; /** * Classes and futures used in {@link FuturesGetCheckedTest} and {@link FuturesGetUncheckedTest}. @@ -58,6 +59,47 @@ final class FuturesGetCheckedInputs { } } + public static final class ExceptionWithManyConstructorsButOnlyOneThrowable extends Exception { + @CheckForNull private Throwable antecedent; + + public ExceptionWithManyConstructorsButOnlyOneThrowable(String message, String a1) { + super(message); + } + + public ExceptionWithManyConstructorsButOnlyOneThrowable(String message, String a1, String a2) { + super(message); + } + + public ExceptionWithManyConstructorsButOnlyOneThrowable( + String message, String a1, String a2, String a3) { + super(message); + } + + public ExceptionWithManyConstructorsButOnlyOneThrowable(String message, Throwable antecedent) { + super(message); + this.antecedent = antecedent; + } + + public ExceptionWithManyConstructorsButOnlyOneThrowable( + String message, String a1, String a2, String a3, String a4) { + super(message); + } + + public ExceptionWithManyConstructorsButOnlyOneThrowable( + String message, String a1, String a2, String a3, String a4, String a5) { + super(message); + } + + public ExceptionWithManyConstructorsButOnlyOneThrowable( + String message, String a1, String a2, String a3, String a4, String a5, String a6) { + super(message); + } + + public Throwable getAntecedent() { + return antecedent; + } + } + @SuppressWarnings("unused") // we're testing that they're not used public static final class ExceptionWithSomePrivateConstructors extends Exception { private ExceptionWithSomePrivateConstructors(String a) {} diff --git a/android/guava-tests/test/com/google/common/util/concurrent/FuturesGetCheckedTest.java b/android/guava-tests/test/com/google/common/util/concurrent/FuturesGetCheckedTest.java index 666a18929..fa615133a 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/FuturesGetCheckedTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/FuturesGetCheckedTest.java @@ -30,11 +30,13 @@ import static com.google.common.util.concurrent.FuturesGetCheckedInputs.RUNTIME_ import static com.google.common.util.concurrent.FuturesGetCheckedInputs.RUNTIME_EXCEPTION_FUTURE; import static com.google.common.util.concurrent.FuturesGetCheckedInputs.UNCHECKED_EXCEPTION; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.testing.GcFinalization; import com.google.common.util.concurrent.FuturesGetCheckedInputs.ExceptionWithBadConstructor; import com.google.common.util.concurrent.FuturesGetCheckedInputs.ExceptionWithGoodAndBadConstructor; import com.google.common.util.concurrent.FuturesGetCheckedInputs.ExceptionWithManyConstructors; +import com.google.common.util.concurrent.FuturesGetCheckedInputs.ExceptionWithManyConstructorsButOnlyOneThrowable; import com.google.common.util.concurrent.FuturesGetCheckedInputs.ExceptionWithPrivateConstructor; import com.google.common.util.concurrent.FuturesGetCheckedInputs.ExceptionWithSomePrivateConstructors; import com.google.common.util.concurrent.FuturesGetCheckedInputs.ExceptionWithWrongTypesConstructor; @@ -74,57 +76,49 @@ public class FuturesGetCheckedTest extends TestCase { public void testGetCheckedUntimed_cancelled() throws TwoArgConstructorException { SettableFuture<String> future = SettableFuture.create(); future.cancel(true); - try { - getChecked(future, TwoArgConstructorException.class); - fail(); - } catch (CancellationException expected) { - } + assertThrows( + CancellationException.class, () -> getChecked(future, TwoArgConstructorException.class)); } public void testGetCheckedUntimed_ExecutionExceptionChecked() { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, TwoArgConstructorException.class); - fail(); - } catch (TwoArgConstructorException expected) { - assertThat(expected).hasCauseThat().isEqualTo(CHECKED_EXCEPTION); - } + TwoArgConstructorException expected = + assertThrows( + TwoArgConstructorException.class, + () -> getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, TwoArgConstructorException.class)); + assertThat(expected).hasCauseThat().isEqualTo(CHECKED_EXCEPTION); } public void testGetCheckedUntimed_ExecutionExceptionUnchecked() throws TwoArgConstructorException { - try { - getChecked(FAILED_FUTURE_UNCHECKED_EXCEPTION, TwoArgConstructorException.class); - fail(); - } catch (UncheckedExecutionException expected) { - assertThat(expected).hasCauseThat().isEqualTo(UNCHECKED_EXCEPTION); - } + UncheckedExecutionException expected = + assertThrows( + UncheckedExecutionException.class, + () -> getChecked(FAILED_FUTURE_UNCHECKED_EXCEPTION, TwoArgConstructorException.class)); + assertThat(expected).hasCauseThat().isEqualTo(UNCHECKED_EXCEPTION); } public void testGetCheckedUntimed_ExecutionExceptionError() throws TwoArgConstructorException { - try { - getChecked(FAILED_FUTURE_ERROR, TwoArgConstructorException.class); - fail(); - } catch (ExecutionError expected) { - assertThat(expected).hasCauseThat().isEqualTo(ERROR); - } + ExecutionError expected = + assertThrows( + ExecutionError.class, + () -> getChecked(FAILED_FUTURE_ERROR, TwoArgConstructorException.class)); + assertThat(expected).hasCauseThat().isEqualTo(ERROR); } public void testGetCheckedUntimed_ExecutionExceptionOtherThrowable() { - try { - getChecked(FAILED_FUTURE_OTHER_THROWABLE, TwoArgConstructorException.class); - fail(); - } catch (TwoArgConstructorException expected) { - assertThat(expected).hasCauseThat().isEqualTo(OTHER_THROWABLE); - } + TwoArgConstructorException expected = + assertThrows( + TwoArgConstructorException.class, + () -> getChecked(FAILED_FUTURE_OTHER_THROWABLE, TwoArgConstructorException.class)); + assertThat(expected).hasCauseThat().isEqualTo(OTHER_THROWABLE); } public void testGetCheckedUntimed_RuntimeException() throws TwoArgConstructorException { - try { - getChecked(RUNTIME_EXCEPTION_FUTURE, TwoArgConstructorException.class); - fail(); - } catch (RuntimeException expected) { - assertEquals(RUNTIME_EXCEPTION, expected); - } + RuntimeException expected = + assertThrows( + RuntimeException.class, + () -> getChecked(RUNTIME_EXCEPTION_FUTURE, TwoArgConstructorException.class)); + assertEquals(RUNTIME_EXCEPTION, expected); } public void testGetCheckedUntimed_Error() throws TwoArgConstructorException { @@ -139,29 +133,26 @@ public class FuturesGetCheckedTest extends TestCase { public void testGetCheckedUntimed_badExceptionConstructor_failsEvenForSuccessfulInput() throws Exception { - try { - getChecked(immediateFuture("x"), ExceptionWithBadConstructor.class); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> getChecked(immediateFuture("x"), ExceptionWithBadConstructor.class)); } public void testGetCheckedUntimed_badExceptionConstructor_wrapsOriginalChecked() throws Exception { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithBadConstructor.class); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithBadConstructor.class)); } public void testGetCheckedUntimed_withGoodAndBadExceptionConstructor() throws Exception { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithGoodAndBadConstructor.class); - fail(); - } catch (ExceptionWithGoodAndBadConstructor expected) { - assertThat(expected).hasCauseThat().isSameInstanceAs(CHECKED_EXCEPTION); - } + ExceptionWithGoodAndBadConstructor expected = + assertThrows( + ExceptionWithGoodAndBadConstructor.class, + () -> + getChecked( + FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithGoodAndBadConstructor.class)); + assertThat(expected).hasCauseThat().isSameInstanceAs(CHECKED_EXCEPTION); } // Boring timed-get tests: @@ -188,56 +179,59 @@ public class FuturesGetCheckedTest extends TestCase { public void testGetCheckedTimed_cancelled() throws TwoArgConstructorException { SettableFuture<String> future = SettableFuture.create(); future.cancel(true); - try { - getChecked(future, TwoArgConstructorException.class, 0, SECONDS); - fail(); - } catch (CancellationException expected) { - } + assertThrows( + CancellationException.class, + () -> getChecked(future, TwoArgConstructorException.class, 0, SECONDS)); } public void testGetCheckedTimed_ExecutionExceptionChecked() { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, TwoArgConstructorException.class, 0, SECONDS); - fail(); - } catch (TwoArgConstructorException expected) { - assertThat(expected).hasCauseThat().isEqualTo(CHECKED_EXCEPTION); - } + TwoArgConstructorException expected = + assertThrows( + TwoArgConstructorException.class, + () -> + getChecked( + FAILED_FUTURE_CHECKED_EXCEPTION, TwoArgConstructorException.class, 0, SECONDS)); + assertThat(expected).hasCauseThat().isEqualTo(CHECKED_EXCEPTION); } public void testGetCheckedTimed_ExecutionExceptionUnchecked() throws TwoArgConstructorException { - try { - getChecked(FAILED_FUTURE_UNCHECKED_EXCEPTION, TwoArgConstructorException.class, 0, SECONDS); - fail(); - } catch (UncheckedExecutionException expected) { - assertThat(expected).hasCauseThat().isEqualTo(UNCHECKED_EXCEPTION); - } + UncheckedExecutionException expected = + assertThrows( + UncheckedExecutionException.class, + () -> + getChecked( + FAILED_FUTURE_UNCHECKED_EXCEPTION, + TwoArgConstructorException.class, + 0, + SECONDS)); + assertThat(expected).hasCauseThat().isEqualTo(UNCHECKED_EXCEPTION); } public void testGetCheckedTimed_ExecutionExceptionError() throws TwoArgConstructorException { - try { - getChecked(FAILED_FUTURE_ERROR, TwoArgConstructorException.class, 0, SECONDS); - fail(); - } catch (ExecutionError expected) { - assertThat(expected).hasCauseThat().isEqualTo(ERROR); - } + ExecutionError expected = + assertThrows( + ExecutionError.class, + () -> getChecked(FAILED_FUTURE_ERROR, TwoArgConstructorException.class, 0, SECONDS)); + assertThat(expected).hasCauseThat().isEqualTo(ERROR); } public void testGetCheckedTimed_ExecutionExceptionOtherThrowable() { - try { - getChecked(FAILED_FUTURE_OTHER_THROWABLE, TwoArgConstructorException.class, 0, SECONDS); - fail(); - } catch (TwoArgConstructorException expected) { - assertThat(expected).hasCauseThat().isEqualTo(OTHER_THROWABLE); - } + TwoArgConstructorException expected = + assertThrows( + TwoArgConstructorException.class, + () -> + getChecked( + FAILED_FUTURE_OTHER_THROWABLE, TwoArgConstructorException.class, 0, SECONDS)); + assertThat(expected).hasCauseThat().isEqualTo(OTHER_THROWABLE); } public void testGetCheckedTimed_RuntimeException() throws TwoArgConstructorException { - try { - getChecked(RUNTIME_EXCEPTION_FUTURE, TwoArgConstructorException.class, 0, SECONDS); - fail(); - } catch (RuntimeException expected) { - assertEquals(RUNTIME_EXCEPTION, expected); - } + RuntimeException expected = + assertThrows( + RuntimeException.class, + () -> + getChecked(RUNTIME_EXCEPTION_FUTURE, TwoArgConstructorException.class, 0, SECONDS)); + assertEquals(RUNTIME_EXCEPTION, expected); } public void testGetCheckedTimed_Error() throws TwoArgConstructorException { @@ -252,101 +246,109 @@ public class FuturesGetCheckedTest extends TestCase { public void testGetCheckedTimed_TimeoutException() { SettableFuture<String> future = SettableFuture.create(); - try { - getChecked(future, TwoArgConstructorException.class, 0, SECONDS); - fail(); - } catch (TwoArgConstructorException expected) { - assertThat(expected).hasCauseThat().isInstanceOf(TimeoutException.class); - } + TwoArgConstructorException expected = + assertThrows( + TwoArgConstructorException.class, + () -> getChecked(future, TwoArgConstructorException.class, 0, SECONDS)); + assertThat(expected).hasCauseThat().isInstanceOf(TimeoutException.class); } public void testGetCheckedTimed_badExceptionConstructor_failsEvenForSuccessfulInput() throws Exception { - try { - getChecked(immediateFuture("x"), ExceptionWithBadConstructor.class, 1, TimeUnit.SECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> + getChecked( + immediateFuture("x"), ExceptionWithBadConstructor.class, 1, TimeUnit.SECONDS)); } public void testGetCheckedTimed_badExceptionConstructor_wrapsOriginalChecked() throws Exception { - try { - getChecked( - FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithBadConstructor.class, 1, TimeUnit.SECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> + getChecked( + FAILED_FUTURE_CHECKED_EXCEPTION, + ExceptionWithBadConstructor.class, + 1, + TimeUnit.SECONDS)); } public void testGetCheckedTimed_withGoodAndBadExceptionConstructor() { - try { - getChecked( - FAILED_FUTURE_CHECKED_EXCEPTION, - ExceptionWithGoodAndBadConstructor.class, - 1, - TimeUnit.SECONDS); - fail(); - } catch (ExceptionWithGoodAndBadConstructor expected) { - assertThat(expected).hasCauseThat().isSameInstanceAs(CHECKED_EXCEPTION); - } + ExceptionWithGoodAndBadConstructor expected = + assertThrows( + ExceptionWithGoodAndBadConstructor.class, + () -> + getChecked( + FAILED_FUTURE_CHECKED_EXCEPTION, + ExceptionWithGoodAndBadConstructor.class, + 1, + TimeUnit.SECONDS)); + assertThat(expected).hasCauseThat().isSameInstanceAs(CHECKED_EXCEPTION); } // Edge case tests of the exception-construction code through untimed get(): @SuppressWarnings("FuturesGetCheckedIllegalExceptionType") public void testGetCheckedUntimed_exceptionClassIsRuntimeException() { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, TwoArgConstructorRuntimeException.class); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, TwoArgConstructorRuntimeException.class)); } public void testGetCheckedUntimed_exceptionClassSomePrivateConstructors() { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithSomePrivateConstructors.class); - fail(); - } catch (ExceptionWithSomePrivateConstructors expected) { - } + assertThrows( + ExceptionWithSomePrivateConstructors.class, + () -> + getChecked( + FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithSomePrivateConstructors.class)); } @SuppressWarnings("FuturesGetCheckedIllegalExceptionType") public void testGetCheckedUntimed_exceptionClassNoPublicConstructor() throws ExceptionWithPrivateConstructor { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithPrivateConstructor.class); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithPrivateConstructor.class)); } @SuppressWarnings("FuturesGetCheckedIllegalExceptionType") public void testGetCheckedUntimed_exceptionClassPublicConstructorWrongType() throws ExceptionWithWrongTypesConstructor { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithWrongTypesConstructor.class); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> + getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithWrongTypesConstructor.class)); } public void testGetCheckedUntimed_exceptionClassPrefersStringConstructor() { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithManyConstructors.class); - fail(); - } catch (ExceptionWithManyConstructors expected) { - assertTrue(expected.usedExpectedConstructor); - } + ExceptionWithManyConstructors expected = + assertThrows( + ExceptionWithManyConstructors.class, + () -> getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithManyConstructors.class)); + assertTrue(expected.usedExpectedConstructor); } public void testGetCheckedUntimed_exceptionClassUsedInitCause() { - try { - getChecked(FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithoutThrowableConstructor.class); - fail(); - } catch (ExceptionWithoutThrowableConstructor expected) { - assertThat(expected).hasMessageThat().contains("mymessage"); - assertThat(expected).hasCauseThat().isEqualTo(CHECKED_EXCEPTION); - } + ExceptionWithoutThrowableConstructor expected = + assertThrows( + ExceptionWithoutThrowableConstructor.class, + () -> + getChecked( + FAILED_FUTURE_CHECKED_EXCEPTION, ExceptionWithoutThrowableConstructor.class)); + assertThat(expected).hasMessageThat().contains("mymessage"); + assertThat(expected).hasCauseThat().isEqualTo(CHECKED_EXCEPTION); + } + + public void testPrefersConstructorWithThrowableParameter() { + ExceptionWithManyConstructorsButOnlyOneThrowable exception = + assertThrows( + ExceptionWithManyConstructorsButOnlyOneThrowable.class, + () -> + getChecked( + FAILED_FUTURE_CHECKED_EXCEPTION, + ExceptionWithManyConstructorsButOnlyOneThrowable.class)); + assertThat(exception).hasMessageThat().contains("mymessage"); + assertThat(exception.getAntecedent()).isEqualTo(CHECKED_EXCEPTION); } // Class unloading test: diff --git a/android/guava-tests/test/com/google/common/util/concurrent/FuturesTransformAsyncTest.java b/android/guava-tests/test/com/google/common/util/concurrent/FuturesTransformAsyncTest.java index 24990200d..e0d579249 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/FuturesTransformAsyncTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/FuturesTransformAsyncTest.java @@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.Futures.transformAsync; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; +import static org.junit.Assert.assertThrows; import com.google.common.util.concurrent.ForwardingListenableFuture.SimpleForwardingListenableFuture; import java.util.concurrent.CancellationException; @@ -82,23 +83,13 @@ public class FuturesTransformAsyncTest extends AbstractChainedListenableFutureTe public void testFutureGetThrowsCancellationIfInputCancelled() throws Exception { inputFuture.cancel(true); // argument is ignored - try { - resultFuture.get(); - fail("Result future must throw CancellationException" + " if input future is cancelled."); - } catch (CancellationException expected) { - } + assertThrows(CancellationException.class, () -> resultFuture.get()); } public void testFutureGetThrowsCancellationIfOutputCancelled() throws Exception { inputFuture.set(SLOW_OUTPUT_VALID_INPUT_DATA); outputFuture.cancel(true); // argument is ignored - try { - resultFuture.get(); - fail( - "Result future must throw CancellationException" - + " if function output future is cancelled."); - } catch (CancellationException expected) { - } + assertThrows(CancellationException.class, () -> resultFuture.get()); } public void testAsyncToString() throws Exception { @@ -111,11 +102,7 @@ public class FuturesTransformAsyncTest extends AbstractChainedListenableFutureTe assertTrue(resultFuture.isCancelled()); assertTrue(inputFuture.isCancelled()); assertFalse(outputFuture.isCancelled()); - try { - resultFuture.get(); - fail("Result future is cancelled and should have thrown a" + " CancellationException"); - } catch (CancellationException expected) { - } + assertThrows(CancellationException.class, () -> resultFuture.get()); } public void testFutureCancellableBeforeOutputCompletion() throws Exception { @@ -124,11 +111,7 @@ public class FuturesTransformAsyncTest extends AbstractChainedListenableFutureTe assertTrue(resultFuture.isCancelled()); assertFalse(inputFuture.isCancelled()); assertTrue(outputFuture.isCancelled()); - try { - resultFuture.get(); - fail("Result future is cancelled and should have thrown a" + " CancellationException"); - } catch (CancellationException expected) { - } + assertThrows(CancellationException.class, () -> resultFuture.get()); } public void testFutureCancellableBeforeFunctionCompletion() throws Exception { @@ -146,20 +129,10 @@ public class FuturesTransformAsyncTest extends AbstractChainedListenableFutureTe assertTrue(resultFuture.isCancelled()); assertFalse(inputFuture.isCancelled()); assertFalse(outputFuture.isCancelled()); - try { - resultFuture.get(); - fail("Result future is cancelled and should have thrown a" + " CancellationException"); - } catch (CancellationException expected) { - } + assertThrows(CancellationException.class, () -> resultFuture.get()); funcCompletionLatch.countDown(); // allow the function to complete - try { - outputFuture.get(); - fail( - "The function output future is cancelled and should have thrown a" - + " CancellationException"); - } catch (CancellationException expected) { - } + assertThrows(CancellationException.class, () -> outputFuture.get()); } public void testFutureCancelAfterCompletion() throws Exception { @@ -174,12 +147,8 @@ public class FuturesTransformAsyncTest extends AbstractChainedListenableFutureTe public void testFutureGetThrowsRuntimeException() throws Exception { BadFuture badInput = new BadFuture(Futures.immediateFuture(20)); ListenableFuture<String> chain = buildChainingFuture(badInput); - try { - chain.get(); - fail("Future.get must throw an exception when the input future fails."); - } catch (ExecutionException e) { - assertSame(RuntimeException.class, e.getCause().getClass()); - } + ExecutionException e = assertThrows(ExecutionException.class, () -> chain.get()); + assertSame(RuntimeException.class, e.getCause().getClass()); } /** Proxy to throw a {@link RuntimeException} out of the {@link #get()} method. */ diff --git a/android/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java b/android/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java index 6d1591354..32bbe0c25 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/InterruptibleTaskTest.java @@ -16,6 +16,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.util.concurrent.InterruptibleTask.Blocker; import java.nio.channels.spi.AbstractInterruptibleChannel; @@ -61,14 +62,10 @@ public final class InterruptibleTaskTest extends TestCase { Thread runner = new Thread(task); runner.start(); isInterruptibleRegistered.await(); - try { - task.interruptTask(); - fail(); - } catch (RuntimeException expected) { - assertThat(expected) - .hasMessageThat() - .isEqualTo("I bet you didn't think Thread.interrupt could throw"); - } + RuntimeException expected = assertThrows(RuntimeException.class, () -> task.interruptTask()); + assertThat(expected) + .hasMessageThat() + .isEqualTo("I bet you didn't think Thread.interrupt could throw"); // We need to wait for the runner to exit. It used to be that the runner would get stuck in the // busy loop when interrupt threw. runner.join(TimeUnit.SECONDS.toMillis(10)); diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTaskTest.java b/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTaskTest.java index fd51a7329..7b501dc3d 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTaskTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTaskTest.java @@ -17,6 +17,7 @@ package com.google.common.util.concurrent; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; +import static org.junit.Assert.assertThrows; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; @@ -113,12 +114,9 @@ public class ListenableFutureTaskTest extends TestCase { runLatch.await(); taskLatch.countDown(); - try { - task.get(5, TimeUnit.SECONDS); - fail("Should have propagated the failure."); - } catch (ExecutionException e) { - assertEquals(IllegalStateException.class, e.getCause().getClass()); - } + ExecutionException e = + assertThrows(ExecutionException.class, () -> task.get(5, TimeUnit.SECONDS)); + assertEquals(IllegalStateException.class, e.getCause().getClass()); assertTrue(listenerLatch.await(5, TimeUnit.SECONDS)); assertTrue(task.isDone()); diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java b/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java index 5c99bc881..b551ff0f8 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/ListenableFutureTester.java @@ -22,6 +22,7 @@ import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; +import static org.junit.Assert.assertThrows; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; @@ -87,11 +88,7 @@ public class ListenableFutureTester { assertTrue(future.isDone()); assertTrue(future.isCancelled()); - try { - future.get(); - fail("Future should throw CancellationException on cancel."); - } catch (CancellationException expected) { - } + assertThrows(CancellationException.class, () -> future.get()); } public void testFailedFuture(@Nullable String message) throws InterruptedException { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java b/android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java index dab6d92f9..ae72e4176 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java @@ -38,6 +38,7 @@ import static com.google.common.util.concurrent.MoreExecutors.renamingDecorator; import static com.google.common.util.concurrent.MoreExecutors.shutdownAndAwaitTermination; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -220,12 +221,7 @@ public class MoreExecutorsTest extends JSR166TestCase { executor.shutdown(); assertTrue(executor.isShutdown()); - try { - executor.submit(doNothingRunnable); - fail("Should have encountered RejectedExecutionException"); - } catch (RejectedExecutionException ex) { - // good to go - } + assertThrows(RejectedExecutionException.class, () -> executor.submit(doNothingRunnable)); assertFalse(executor.isTerminated()); // WAIT #2 @@ -237,12 +233,7 @@ public class MoreExecutorsTest extends JSR166TestCase { assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS)); assertTrue(executor.awaitTermination(0, TimeUnit.SECONDS)); assertTrue(executor.isShutdown()); - try { - executor.submit(doNothingRunnable); - fail("Should have encountered RejectedExecutionException"); - } catch (RejectedExecutionException ex) { - // good to go - } + assertThrows(RejectedExecutionException.class, () -> executor.submit(doNothingRunnable)); assertTrue(executor.isTerminated()); otherThread.join(1000); @@ -309,11 +300,7 @@ public class MoreExecutorsTest extends JSR166TestCase { public void testExecuteAfterShutdown() { ExecutorService executor = newDirectExecutorService(); executor.shutdown(); - try { - executor.execute(EMPTY_RUNNABLE); - fail(); - } catch (RejectedExecutionException expected) { - } + assertThrows(RejectedExecutionException.class, () -> executor.execute(EMPTY_RUNNABLE)); } public <T> void testListeningExecutorServiceInvokeAllJavadocCodeCompiles() throws Exception { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java b/android/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java index a2773ba64..112da6803 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/RateLimiterTest.java @@ -21,6 +21,7 @@ import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableClassToInstanceMap; import com.google.common.collect.ImmutableSet; @@ -75,50 +76,18 @@ public class RateLimiterTest extends TestCase { limiter.setRate(10.0); assertEquals(10.0, limiter.getRate()); - try { - limiter.setRate(0.0); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - limiter.setRate(-10.0); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> limiter.setRate(0.0)); + assertThrows(IllegalArgumentException.class, () -> limiter.setRate(-10.0)); } public void testAcquireParameterValidation() { RateLimiter limiter = RateLimiter.create(999); - try { - limiter.acquire(0); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - limiter.acquire(-1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - limiter.tryAcquire(0); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - limiter.tryAcquire(-1); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - limiter.tryAcquire(0, 1, SECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } - try { - limiter.tryAcquire(-1, 1, SECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> limiter.acquire(0)); + assertThrows(IllegalArgumentException.class, () -> limiter.acquire(-1)); + assertThrows(IllegalArgumentException.class, () -> limiter.tryAcquire(0)); + assertThrows(IllegalArgumentException.class, () -> limiter.tryAcquire(-1)); + assertThrows(IllegalArgumentException.class, () -> limiter.tryAcquire(0, 1, SECONDS)); + assertThrows(IllegalArgumentException.class, () -> limiter.tryAcquire(-1, 1, SECONDS)); } public void testSimpleWithWait() { @@ -169,17 +138,9 @@ public class RateLimiterTest extends TestCase { unused = RateLimiter.create(1.0, 1, NANOSECONDS); unused = RateLimiter.create(1.0, 0, NANOSECONDS); - try { - RateLimiter.create(0.0, 1, NANOSECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> RateLimiter.create(0.0, 1, NANOSECONDS)); - try { - RateLimiter.create(1.0, -1, NANOSECONDS); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> RateLimiter.create(1.0, -1, NANOSECONDS)); } @AndroidIncompatible // difference in String.format rounding? diff --git a/android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java b/android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java index cbb6c1c82..3ebff11c8 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/SequentialExecutorTest.java @@ -19,6 +19,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.MoreExecutors.newSequentialExecutor; import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; +import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @@ -79,11 +80,7 @@ public class SequentialExecutorTest extends TestCase { } public void testConstructingWithNullExecutor_fails() { - try { - new SequentialExecutor(null); - fail("Should have failed with NullPointerException."); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> new SequentialExecutor(null)); } public void testBasics() { @@ -263,11 +260,7 @@ public class SequentialExecutorTest extends TestCase { numCalls.incrementAndGet(); } }; - try { - executor.execute(task); - fail(); - } catch (RejectedExecutionException expected) { - } + assertThrows(RejectedExecutionException.class, () -> executor.execute(task)); assertEquals(0, numCalls.get()); reject.set(false); executor.execute(task); @@ -344,18 +337,11 @@ public class SequentialExecutorTest extends TestCase { } }); future.get(10, TimeUnit.SECONDS); - try { - executor.execute(Runnables.doNothing()); - fail(); - } catch (RejectedExecutionException expected) { - } + assertThrows(RejectedExecutionException.class, () -> executor.execute(Runnables.doNothing())); latch.countDown(); - try { - first.get(10, TimeUnit.SECONDS); - fail(); - } catch (ExecutionException expected) { - assertThat(expected).hasCauseThat().isInstanceOf(RejectedExecutionException.class); - } + ExecutionException expected = + assertThrows(ExecutionException.class, () -> first.get(10, TimeUnit.SECONDS)); + assertThat(expected).hasCauseThat().isInstanceOf(RejectedExecutionException.class); } public void testToString() { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java b/android/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java index 958be1972..02815e3d1 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/ServiceManagerTest.java @@ -16,10 +16,13 @@ package com.google.common.util.concurrent; +import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION; +import static com.google.common.base.StandardSystemProperty.OS_NAME; import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -120,6 +123,10 @@ public class ServiceManagerTest extends TestCase { } public void testServiceStartupTimes() { + if (isWindows() && isJava8()) { + // Flaky there: https://github.com/google/guava/pull/6731#issuecomment-1736298607 + return; + } Service a = new NoOpDelayedService(150); Service b = new NoOpDelayedService(353); ServiceManager serviceManager = new ServiceManager(asList(a, b)); @@ -195,11 +202,7 @@ public class ServiceManagerTest extends TestCase { RecordingListener listener = new RecordingListener(); manager.addListener(listener, directExecutor()); assertState(manager, Service.State.NEW, a, b, c, d, e); - try { - manager.startAsync().awaitHealthy(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> manager.startAsync().awaitHealthy()); assertFalse(listener.healthyCalled); assertState(manager, Service.State.RUNNING, a, c, e); assertEquals(ImmutableSet.of(b, d), listener.failedServices); @@ -219,11 +222,7 @@ public class ServiceManagerTest extends TestCase { RecordingListener listener = new RecordingListener(); manager.addListener(listener, directExecutor()); assertState(manager, Service.State.NEW, a, b); - try { - manager.startAsync().awaitHealthy(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> manager.startAsync().awaitHealthy()); assertTrue(listener.healthyCalled); assertEquals(ImmutableSet.of(b), listener.failedServices); @@ -266,19 +265,11 @@ public class ServiceManagerTest extends TestCase { Service a = new NoOpDelayedService(50); ServiceManager manager = new ServiceManager(asList(a)); manager.startAsync(); - try { - manager.awaitHealthy(1, TimeUnit.MILLISECONDS); - fail(); - } catch (TimeoutException expected) { - } + assertThrows(TimeoutException.class, () -> manager.awaitHealthy(1, TimeUnit.MILLISECONDS)); manager.awaitHealthy(5, SECONDS); // no exception thrown manager.stopAsync(); - try { - manager.awaitStopped(1, TimeUnit.MILLISECONDS); - fail(); - } catch (TimeoutException expected) { - } + assertThrows(TimeoutException.class, () -> manager.awaitStopped(1, TimeUnit.MILLISECONDS)); manager.awaitStopped(5, SECONDS); // no exception thrown } @@ -291,11 +282,7 @@ public class ServiceManagerTest extends TestCase { ServiceManager manager = new ServiceManager(asList(a)); RecordingListener listener = new RecordingListener(); manager.addListener(listener, directExecutor()); - try { - manager.startAsync().awaitHealthy(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> manager.startAsync().awaitHealthy()); assertTrue(listener.stoppedCalled); } @@ -308,11 +295,7 @@ public class ServiceManagerTest extends TestCase { ServiceManager manager = new ServiceManager(asList(a)); RecordingListener listener = new RecordingListener(); manager.addListener(listener, directExecutor()); - try { - manager.startAsync().awaitHealthy(); - fail(); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> manager.startAsync().awaitHealthy()); assertFalse(listener.healthyCalled); } @@ -511,11 +494,7 @@ public class ServiceManagerTest extends TestCase { logger.addHandler(logHandler); NoOpService service = new NoOpService(); service.startAsync(); - try { - new ServiceManager(Arrays.asList(service)); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> new ServiceManager(Arrays.asList(service))); service.stopAsync(); // Nothing was logged! assertEquals(0, logHandler.getStoredLogRecords().size()); @@ -536,6 +515,7 @@ public class ServiceManagerTest extends TestCase { service1.startAsync(); delegate.addListener(listener, executor); } + // Delegates from here on down @Override public final Service startAsync() { @@ -582,12 +562,11 @@ public class ServiceManagerTest extends TestCase { return delegate.failureCause(); } }; - try { - new ServiceManager(Arrays.asList(service1, service2)); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).contains("started transitioning asynchronously"); - } + IllegalArgumentException expected = + assertThrows( + IllegalArgumentException.class, + () -> new ServiceManager(Arrays.asList(service1, service2))); + assertThat(expected.getMessage()).contains("started transitioning asynchronously"); } /** @@ -666,4 +645,12 @@ public class ServiceManagerTest extends TestCase { failedServices.add(service); } } + + private static boolean isWindows() { + return OS_NAME.value().startsWith("Windows"); + } + + private static boolean isJava8() { + return JAVA_SPECIFICATION_VERSION.value().equals("1.8"); + } } diff --git a/android/guava-tests/test/com/google/common/util/concurrent/SettableFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/SettableFutureTest.java index 105e8de04..84b5c6757 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/SettableFutureTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/SettableFutureTest.java @@ -17,6 +17,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; @@ -44,11 +45,7 @@ public class SettableFutureTest extends TestCase { } public void testDefaultState() throws Exception { - try { - future.get(5, TimeUnit.MILLISECONDS); - fail(); - } catch (TimeoutException expected) { - } + assertThrows(TimeoutException.class, () -> future.get(5, TimeUnit.MILLISECONDS)); } public void testSetValue() throws Exception { @@ -62,11 +59,7 @@ public class SettableFutureTest extends TestCase { } public void testSetFailureNull() throws Exception { - try { - future.setException(null); - fail(); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> future.setException(null)); assertFalse(future.isDone()); assertTrue(future.setException(new Exception("failure"))); tester.testFailedFuture("failure"); @@ -108,12 +101,8 @@ public class SettableFutureTest extends TestCase { // Check that the future has been set properly. assertTrue(future.isDone()); assertFalse(future.isCancelled()); - try { - future.get(); - fail("Expected ExecutionException"); - } catch (ExecutionException ee) { - assertThat(ee).hasCauseThat().isSameInstanceAs(e); - } + ExecutionException ee = assertThrows(ExecutionException.class, () -> future.get()); + assertThat(ee).hasCauseThat().isSameInstanceAs(e); } public void testSetFuture() throws Exception { @@ -127,12 +116,7 @@ public class SettableFutureTest extends TestCase { // Check that the future has been set properly. assertFalse(future.isDone()); assertFalse(future.isCancelled()); - try { - future.get(0, TimeUnit.MILLISECONDS); - fail("Expected TimeoutException"); - } catch (TimeoutException expected) { - /* expected */ - } + assertThrows(TimeoutException.class, () -> future.get(0, TimeUnit.MILLISECONDS)); nested.set("foo"); assertTrue(future.isDone()); assertFalse(future.isCancelled()); @@ -154,12 +138,7 @@ public class SettableFutureTest extends TestCase { // Check that the future has been set properly. assertFalse(future.isDone()); assertFalse(future.isCancelled()); - try { - future.get(0, TimeUnit.MILLISECONDS); - fail("Expected TimeoutException"); - } catch (TimeoutException expected) { - /* expected */ - } + assertThrows(TimeoutException.class, () -> future.get(0, TimeUnit.MILLISECONDS)); FooChild value = new FooChild(); nested.set(value); assertTrue(future.isDone()); @@ -173,12 +152,7 @@ public class SettableFutureTest extends TestCase { async.setFuture(inner); inner.cancel(true); assertTrue(async.isCancelled()); - try { - async.get(); - fail("Expected CancellationException"); - } catch (CancellationException expected) { - /* expected */ - } + assertThrows(CancellationException.class, () -> async.get()); } public void testCancel_resultCancelsInner_interrupted() throws Exception { @@ -188,12 +162,7 @@ public class SettableFutureTest extends TestCase { async.cancel(true); assertTrue(inner.isCancelled()); assertTrue(inner.wasInterrupted()); - try { - inner.get(); - fail("Expected CancellationException"); - } catch (CancellationException expected) { - /* expected */ - } + assertThrows(CancellationException.class, () -> inner.get()); } public void testCancel_resultCancelsInner() throws Exception { @@ -203,12 +172,7 @@ public class SettableFutureTest extends TestCase { async.cancel(false); assertTrue(inner.isCancelled()); assertFalse(inner.wasInterrupted()); - try { - inner.get(); - fail("Expected CancellationException"); - } catch (CancellationException expected) { - /* expected */ - } + assertThrows(CancellationException.class, () -> inner.get()); } public void testCancel_beforeSet() throws Exception { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java b/android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java index 37ef84f66..f66b9ed47 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/SimpleTimeLimiterTest.java @@ -18,6 +18,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.base.Stopwatch; import com.google.common.collect.Range; @@ -108,11 +109,7 @@ public class SimpleTimeLimiterTest extends TestCase { Sample proxy = service.newProxy(target, Sample.class, NOT_ENOUGH_MS, MILLISECONDS); Stopwatch stopwatch = Stopwatch.createStarted(); - try { - proxy.sleepThenReturnInput("x"); - fail("no exception thrown"); - } catch (UncheckedTimeoutException expected) { - } + assertThrows(UncheckedTimeoutException.class, () -> proxy.sleepThenReturnInput("x")); assertThat(stopwatch.elapsed(MILLISECONDS)).isIn(Range.closed(NOT_ENOUGH_MS, DELAY_MS * 2)); // Is it still computing away anyway? @@ -126,11 +123,7 @@ public class SimpleTimeLimiterTest extends TestCase { Sample proxy = service.newProxy(target, Sample.class, ENOUGH_MS, MILLISECONDS); Stopwatch stopwatch = Stopwatch.createStarted(); - try { - proxy.sleepThenThrowException(); - fail("no exception thrown"); - } catch (SampleException expected) { - } + assertThrows(SampleException.class, () -> proxy.sleepThenThrowException()); assertThat(stopwatch.elapsed(MILLISECONDS)).isIn(Range.closed(DELAY_MS, ENOUGH_MS)); } @@ -140,11 +133,7 @@ public class SimpleTimeLimiterTest extends TestCase { Sample proxy = service.newProxy(target, Sample.class, NOT_ENOUGH_MS, MILLISECONDS); Stopwatch stopwatch = Stopwatch.createStarted(); - try { - proxy.sleepThenThrowException(); - fail("no exception thrown"); - } catch (UncheckedTimeoutException expected) { - } + assertThrows(UncheckedTimeoutException.class, () -> proxy.sleepThenThrowException()); assertThat(stopwatch.elapsed(MILLISECONDS)).isIn(Range.closed(NOT_ENOUGH_MS, DELAY_MS * 2)); } @@ -159,20 +148,17 @@ public class SimpleTimeLimiterTest extends TestCase { } public void testCallWithTimeout_goodCallableWithNotEnoughTime() throws Exception { - try { - service.callWithTimeout(GOOD_CALLABLE, NOT_ENOUGH_MS, MILLISECONDS); - fail("no exception thrown"); - } catch (TimeoutException expected) { - } + assertThrows( + TimeoutException.class, + () -> service.callWithTimeout(GOOD_CALLABLE, NOT_ENOUGH_MS, MILLISECONDS)); } public void testCallWithTimeout_badCallableWithEnoughTime() throws Exception { - try { - service.callWithTimeout(BAD_CALLABLE, ENOUGH_MS, MILLISECONDS); - fail("no exception thrown"); - } catch (ExecutionException expected) { - assertThat(expected.getCause()).isInstanceOf(SampleException.class); - } + ExecutionException expected = + assertThrows( + ExecutionException.class, + () -> service.callWithTimeout(BAD_CALLABLE, ENOUGH_MS, MILLISECONDS)); + assertThat(expected.getCause()).isInstanceOf(SampleException.class); } public void testCallUninterruptiblyWithTimeout_goodCallableWithEnoughTime() throws Exception { @@ -185,20 +171,17 @@ public class SimpleTimeLimiterTest extends TestCase { } public void testCallUninterruptiblyWithTimeout_goodCallableWithNotEnoughTime() throws Exception { - try { - service.callUninterruptiblyWithTimeout(GOOD_CALLABLE, NOT_ENOUGH_MS, MILLISECONDS); - fail("no exception thrown"); - } catch (TimeoutException expected) { - } + assertThrows( + TimeoutException.class, + () -> service.callUninterruptiblyWithTimeout(GOOD_CALLABLE, NOT_ENOUGH_MS, MILLISECONDS)); } public void testCallUninterruptiblyWithTimeout_badCallableWithEnoughTime() throws Exception { - try { - service.callUninterruptiblyWithTimeout(BAD_CALLABLE, ENOUGH_MS, MILLISECONDS); - fail("no exception thrown"); - } catch (ExecutionException expected) { - assertThat(expected.getCause()).isInstanceOf(SampleException.class); - } + ExecutionException expected = + assertThrows( + ExecutionException.class, + () -> service.callUninterruptiblyWithTimeout(BAD_CALLABLE, ENOUGH_MS, MILLISECONDS)); + assertThat(expected.getCause()).isInstanceOf(SampleException.class); } public void testRunWithTimeout_goodRunnableWithEnoughTime() throws Exception { @@ -210,20 +193,17 @@ public class SimpleTimeLimiterTest extends TestCase { } public void testRunWithTimeout_goodRunnableWithNotEnoughTime() throws Exception { - try { - service.runWithTimeout(GOOD_RUNNABLE, NOT_ENOUGH_MS, MILLISECONDS); - fail("no exception thrown"); - } catch (TimeoutException expected) { - } + assertThrows( + TimeoutException.class, + () -> service.runWithTimeout(GOOD_RUNNABLE, NOT_ENOUGH_MS, MILLISECONDS)); } public void testRunWithTimeout_badRunnableWithEnoughTime() throws Exception { - try { - service.runWithTimeout(BAD_RUNNABLE, ENOUGH_MS, MILLISECONDS); - fail("no exception thrown"); - } catch (UncheckedExecutionException expected) { - assertThat(expected.getCause()).isInstanceOf(SampleRuntimeException.class); - } + UncheckedExecutionException expected = + assertThrows( + UncheckedExecutionException.class, + () -> service.runWithTimeout(BAD_RUNNABLE, ENOUGH_MS, MILLISECONDS)); + assertThat(expected.getCause()).isInstanceOf(SampleRuntimeException.class); } public void testRunUninterruptiblyWithTimeout_goodRunnableWithEnoughTime() throws Exception { @@ -235,20 +215,17 @@ public class SimpleTimeLimiterTest extends TestCase { } public void testRunUninterruptiblyWithTimeout_goodRunnableWithNotEnoughTime() throws Exception { - try { - service.runUninterruptiblyWithTimeout(GOOD_RUNNABLE, NOT_ENOUGH_MS, MILLISECONDS); - fail("no exception thrown"); - } catch (TimeoutException expected) { - } + assertThrows( + TimeoutException.class, + () -> service.runUninterruptiblyWithTimeout(GOOD_RUNNABLE, NOT_ENOUGH_MS, MILLISECONDS)); } public void testRunUninterruptiblyWithTimeout_badRunnableWithEnoughTime() throws Exception { - try { - service.runUninterruptiblyWithTimeout(BAD_RUNNABLE, ENOUGH_MS, MILLISECONDS); - fail("no exception thrown"); - } catch (UncheckedExecutionException expected) { - assertThat(expected.getCause()).isInstanceOf(SampleRuntimeException.class); - } + UncheckedExecutionException expected = + assertThrows( + UncheckedExecutionException.class, + () -> service.runUninterruptiblyWithTimeout(BAD_RUNNABLE, ENOUGH_MS, MILLISECONDS)); + assertThat(expected.getCause()).isInstanceOf(SampleRuntimeException.class); } private interface Sample { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/SupplementalMonitorTest.java b/android/guava-tests/test/com/google/common/util/concurrent/SupplementalMonitorTest.java index 5b77f9a59..62b69aec7 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/SupplementalMonitorTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/SupplementalMonitorTest.java @@ -18,6 +18,7 @@ package com.google.common.util.concurrent; import static com.google.common.util.concurrent.GeneratedMonitorTest.startThread; import static com.google.common.util.concurrent.Uninterruptibles.joinUninterruptibly; +import static org.junit.Assert.assertThrows; import com.google.common.util.concurrent.GeneratedMonitorTest.FlagGuard; import java.util.concurrent.atomic.AtomicBoolean; @@ -37,41 +38,25 @@ public class SupplementalMonitorTest extends TestCase { public void testLeaveWithoutEnterThrowsIMSE() { Monitor monitor = new Monitor(); - try { - monitor.leave(); - fail("expected IllegalMonitorStateException"); - } catch (IllegalMonitorStateException expected) { - } + assertThrows(IllegalMonitorStateException.class, () -> monitor.leave()); } public void testGetWaitQueueLengthWithWrongMonitorThrowsIMSE() { Monitor monitor1 = new Monitor(); Monitor monitor2 = new Monitor(); FlagGuard guard = new FlagGuard(monitor2); - try { - monitor1.getWaitQueueLength(guard); - fail("expected IllegalMonitorStateException"); - } catch (IllegalMonitorStateException expected) { - } + assertThrows(IllegalMonitorStateException.class, () -> monitor1.getWaitQueueLength(guard)); } public void testHasWaitersWithWrongMonitorThrowsIMSE() { Monitor monitor1 = new Monitor(); Monitor monitor2 = new Monitor(); FlagGuard guard = new FlagGuard(monitor2); - try { - monitor1.hasWaiters(guard); - fail("expected IllegalMonitorStateException"); - } catch (IllegalMonitorStateException expected) { - } + assertThrows(IllegalMonitorStateException.class, () -> monitor1.hasWaiters(guard)); } public void testNullMonitorInGuardConstructorThrowsNPE() { - try { - new FlagGuard(null); - fail("expected NullPointerException"); - } catch (NullPointerException expected) { - } + assertThrows(NullPointerException.class, () -> new FlagGuard(null)); } public void testIsFair() { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java b/android/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java index a3a7b8e79..09b3ec7ee 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/ThreadFactoryBuilderTest.java @@ -17,6 +17,7 @@ package com.google.common.util.concurrent; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.common.testing.NullPointerTester; import java.lang.Thread.UncaughtExceptionHandler; @@ -129,19 +130,13 @@ public class ThreadFactoryBuilderTest extends TestCase { } public void testPriority_tooLow() { - try { - builder.setPriority(Thread.MIN_PRIORITY - 1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> builder.setPriority(Thread.MIN_PRIORITY - 1)); } public void testPriority_tooHigh() { - try { - builder.setPriority(Thread.MAX_PRIORITY + 1); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, () -> builder.setPriority(Thread.MAX_PRIORITY + 1)); } public void testUncaughtExceptionHandler_custom() { diff --git a/android/guava-tests/test/com/google/common/util/concurrent/UninterruptibleFutureTest.java b/android/guava-tests/test/com/google/common/util/concurrent/UninterruptibleFutureTest.java index 3f91b8123..f857c6edf 100644 --- a/android/guava-tests/test/com/google/common/util/concurrent/UninterruptibleFutureTest.java +++ b/android/guava-tests/test/com/google/common/util/concurrent/UninterruptibleFutureTest.java @@ -20,6 +20,7 @@ import static com.google.common.util.concurrent.InterruptionUtil.repeatedlyInter import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertThrows; import com.google.common.testing.TearDown; import com.google.common.testing.TearDownStack; @@ -120,11 +121,9 @@ public class UninterruptibleFutureTest extends TestCase { repeatedlyInterruptTestThread(100, tearDownStack); - try { - getUninterruptibly(delayedFuture, 500, TimeUnit.MILLISECONDS); - fail("expected to time out"); - } catch (TimeoutException expected) { - } + assertThrows( + TimeoutException.class, + () -> getUninterruptibly(delayedFuture, 500, TimeUnit.MILLISECONDS)); assertTrue(Thread.interrupted()); // clears the interrupt state, too assertFalse(sleeper.completed); @@ -217,13 +216,9 @@ public class UninterruptibleFutureTest extends TestCase { Thread waitingThread = new Thread(wasInterrupted); waitingThread.start(); waitingThread.interrupt(); - try { - wasInterrupted.get(); - fail(); - } catch (ExecutionException expected) { - assertTrue( - expected.getCause().toString(), expected.getCause() instanceof InterruptedException); - } + ExecutionException expected = + assertThrows(ExecutionException.class, () -> wasInterrupted.get()); + assertTrue(expected.getCause().toString(), expected.getCause() instanceof InterruptedException); } public void testMakeUninterruptible_timedGetZeroTimeoutAttempted() |