diff --git a/api/src/test/java/io/grpc/ContextsTest.java b/api/src/test/java/io/grpc/ContextsTest.java index 185100685c8..848c867bc5b 100644 --- a/api/src/test/java/io/grpc/ContextsTest.java +++ b/api/src/test/java/io/grpc/ContextsTest.java @@ -18,13 +18,13 @@ import static io.grpc.Contexts.interceptCall; import static io.grpc.Contexts.statusFromCancelled; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -49,6 +49,7 @@ public class ContextsTest { private static Context.Key contextKey = Context.key("key"); /** For use in comparing context by reference. */ private Context uniqueContext = Context.ROOT.withValue(contextKey, new Object()); + @SuppressWarnings("unchecked") private ServerCall call = new NoopServerCall<>(); private Metadata headers = new Metadata(); diff --git a/api/src/test/java/io/grpc/MetadataTest.java b/api/src/test/java/io/grpc/MetadataTest.java index c9095a82d5a..48d3b05ede7 100644 --- a/api/src/test/java/io/grpc/MetadataTest.java +++ b/api/src/test/java/io/grpc/MetadataTest.java @@ -38,9 +38,8 @@ import java.util.Arrays; import java.util.Iterator; import java.util.Locale; -import org.junit.Rule; +import org.junit.Assert; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -50,8 +49,6 @@ @RunWith(JUnit4.class) public class MetadataTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - private static final Metadata.BinaryMarshaller FISH_MARSHALLER = new Metadata.BinaryMarshaller() { @Override @@ -121,10 +118,12 @@ public Fish parseStream(InputStream stream) { @Test public void noPseudoHeaders() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid character"); - - Metadata.Key.of(":test-bin", FISH_MARSHALLER); + try { + Metadata.Key.of(":test-bin", FISH_MARSHALLER); + Assert.fail(); + } catch (IllegalArgumentException ex) { + assertEquals("Invalid character ':' in key name ':test-bin'", ex.getMessage()); + } } @Test @@ -186,8 +185,12 @@ public void testGetAllNoRemove() { Iterator i = metadata.getAll(KEY).iterator(); assertEquals(lance, i.next()); - thrown.expect(UnsupportedOperationException.class); - i.remove(); + try { + i.remove(); + Assert.fail(); + } catch (UnsupportedOperationException expected) { + + } } @Test @@ -271,17 +274,24 @@ public void mergeExpands() { @Test public void shortBinaryKeyName() { - thrown.expect(IllegalArgumentException.class); - Metadata.Key.of("-bin", FISH_MARSHALLER); + try { + Metadata.Key.of("-bin", FISH_MARSHALLER); + Assert.fail(); + } catch (IllegalArgumentException expected) { + + } } @Test public void invalidSuffixBinaryKeyName() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Binary header is named"); - - Metadata.Key.of("nonbinary", FISH_MARSHALLER); + try { + Metadata.Key.of("nonbinary", FISH_MARSHALLER); + Assert.fail(); + } catch (IllegalArgumentException expected) { + Assert.assertEquals("Binary header is named nonbinary. It must end with -bin", + expected.getMessage()); + } } @Test diff --git a/api/src/test/java/io/grpc/MethodDescriptorTest.java b/api/src/test/java/io/grpc/MethodDescriptorTest.java index 68637648ce4..ce8e42f0b2c 100644 --- a/api/src/test/java/io/grpc/MethodDescriptorTest.java +++ b/api/src/test/java/io/grpc/MethodDescriptorTest.java @@ -26,9 +26,7 @@ import io.grpc.MethodDescriptor.Marshaller; import io.grpc.MethodDescriptor.MethodType; import io.grpc.testing.TestMethodDescriptors; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -37,8 +35,6 @@ */ @RunWith(JUnit4.class) public class MethodDescriptorTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); @Test public void createMethodDescriptor() { diff --git a/api/src/test/java/io/grpc/ServerInterceptorsTest.java b/api/src/test/java/io/grpc/ServerInterceptorsTest.java index 4d17338119a..24ab2a55d0e 100644 --- a/api/src/test/java/io/grpc/ServerInterceptorsTest.java +++ b/api/src/test/java/io/grpc/ServerInterceptorsTest.java @@ -38,10 +38,10 @@ import java.util.Arrays; import java.util.List; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentMatchers; @@ -56,9 +56,6 @@ public class ServerInterceptorsTest { @Rule public final MockitoRule mocks = MockitoJUnit.rule(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Mock private Marshaller requestMarshaller; @@ -111,21 +108,32 @@ public void makeSureExpectedMocksUnused() { public void npeForNullServiceDefinition() { ServerServiceDefinition serviceDef = null; List interceptors = Arrays.asList(); - thrown.expect(NullPointerException.class); - ServerInterceptors.intercept(serviceDef, interceptors); + + try { + ServerInterceptors.intercept(serviceDef, interceptors); + Assert.fail(); + } catch (NullPointerException expected) { + } } @Test public void npeForNullInterceptorList() { - thrown.expect(NullPointerException.class); - ServerInterceptors.intercept(serviceDefinition, (List) null); + + try { + ServerInterceptors.intercept(serviceDefinition, (List) null); + Assert.fail(); + } catch (NullPointerException expected) { + } } @Test public void npeForNullInterceptor() { List interceptors = Arrays.asList((ServerInterceptor) null); - thrown.expect(NullPointerException.class); - ServerInterceptors.intercept(serviceDefinition, interceptors); + try { + ServerInterceptors.intercept(serviceDefinition, interceptors); + Assert.fail(); + } catch (NullPointerException expected) { + } } @Test diff --git a/api/src/test/java/io/grpc/ServerServiceDefinitionTest.java b/api/src/test/java/io/grpc/ServerServiceDefinitionTest.java index 3078d44a6e7..73359fe635a 100644 --- a/api/src/test/java/io/grpc/ServerServiceDefinitionTest.java +++ b/api/src/test/java/io/grpc/ServerServiceDefinitionTest.java @@ -23,9 +23,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; -import org.junit.Rule; +import org.junit.Assert; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -52,8 +51,6 @@ public class ServerServiceDefinitionTest { = ServerMethodDefinition.create(method1, methodHandler1); private ServerMethodDefinition methodDef2 = ServerMethodDefinition.create(method2, methodHandler2); - @Rule - public ExpectedException thrown = ExpectedException.none(); @Test public void noMethods() { @@ -90,9 +87,13 @@ public void addMethod_duplicateName() { ServiceDescriptor sd = new ServiceDescriptor(serviceName, method1); ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd) .addMethod(method1, methodHandler1); - thrown.expect(IllegalStateException.class); - ssd.addMethod(diffMethod1, methodHandler2) - .build(); + try { + ssd.addMethod(diffMethod1, methodHandler2) + .build(); + Assert.fail(); + } catch (IllegalStateException expected) { + + } } @Test @@ -100,8 +101,11 @@ public void buildMisaligned_extraMethod() { ServiceDescriptor sd = new ServiceDescriptor(serviceName); ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd) .addMethod(methodDef1); - thrown.expect(IllegalStateException.class); - ssd.build(); + try { + ssd.build(); + Assert.fail(); + } catch (IllegalStateException expected) { + } } @Test @@ -109,16 +113,22 @@ public void buildMisaligned_diffMethodInstance() { ServiceDescriptor sd = new ServiceDescriptor(serviceName, method1); ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd) .addMethod(diffMethod1, methodHandler1); - thrown.expect(IllegalStateException.class); - ssd.build(); + try { + ssd.build(); + Assert.fail(); + } catch (IllegalStateException expected) { + } } @Test public void buildMisaligned_missingMethod() { ServiceDescriptor sd = new ServiceDescriptor(serviceName, method1); ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd); - thrown.expect(IllegalStateException.class); - ssd.build(); + try { + ssd.build(); + Assert.fail(); + } catch (IllegalStateException expected) { + } } @Test diff --git a/api/src/test/java/io/grpc/ServiceDescriptorTest.java b/api/src/test/java/io/grpc/ServiceDescriptorTest.java index 0ba64e3676c..e84cb021ce8 100644 --- a/api/src/test/java/io/grpc/ServiceDescriptorTest.java +++ b/api/src/test/java/io/grpc/ServiceDescriptorTest.java @@ -17,6 +17,7 @@ package io.grpc; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import io.grpc.MethodDescriptor.MethodType; import io.grpc.testing.TestMethodDescriptors; @@ -24,9 +25,8 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import org.junit.Rule; +import org.junit.Assert; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -36,31 +36,34 @@ @RunWith(JUnit4.class) public class ServiceDescriptorTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void failsOnNullName() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("name"); - - new ServiceDescriptor(null, Collections.>emptyList()); + try { + new ServiceDescriptor(null, Collections.>emptyList()); + Assert.fail(); + } catch (NullPointerException ex) { + Assert.assertEquals("name", ex.getMessage()); + } } @Test public void failsOnNullMethods() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("methods"); - - new ServiceDescriptor("name", (Collection>) null); + try { + new ServiceDescriptor("name", (Collection>) null); + Assert.fail(); + } catch (NullPointerException ex) { + Assert.assertEquals("methods", ex.getMessage()); + } } @Test public void failsOnNullMethod() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("method"); - - new ServiceDescriptor("name", Collections.>singletonList(null)); + try { + new ServiceDescriptor("name", Collections.>singletonList(null)); + Assert.fail(); + } catch (NullPointerException ex) { + Assert.assertEquals("method", ex.getMessage()); + } } @Test @@ -73,10 +76,12 @@ public void failsOnNonMatchingNames() { .setResponseMarshaller(TestMethodDescriptors.voidMarshaller()) .build()); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("service names"); - - new ServiceDescriptor("name", descriptors); + try { + new ServiceDescriptor("name", descriptors); + Assert.fail(); + } catch (IllegalArgumentException ex) { + Assert.assertEquals("service names wrongservice != name", ex.getMessage()); + } } @Test @@ -95,10 +100,12 @@ public void failsOnNonDuplicateNames() { .setResponseMarshaller(TestMethodDescriptors.voidMarshaller()) .build()); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("duplicate"); - - new ServiceDescriptor("name", descriptors); + try { + new ServiceDescriptor("name", descriptors); + fail(); + } catch (IllegalArgumentException ex) { + Assert.assertEquals("duplicate name name/method", ex.getMessage()); + } } @Test diff --git a/context/src/test/java/io/grpc/ContextTest.java b/context/src/test/java/io/grpc/ContextTest.java index bf078fcff92..5171d4839a9 100644 --- a/context/src/test/java/io/grpc/ContextTest.java +++ b/context/src/test/java/io/grpc/ContextTest.java @@ -17,6 +17,7 @@ package io.grpc; import static io.grpc.Context.cancellableAncestor; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -24,7 +25,6 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; diff --git a/core/src/test/java/io/grpc/internal/AbstractClientStreamTest.java b/core/src/test/java/io/grpc/internal/AbstractClientStreamTest.java index 7ce6b421167..f28fc1c4d76 100644 --- a/core/src/test/java/io/grpc/internal/AbstractClientStreamTest.java +++ b/core/src/test/java/io/grpc/internal/AbstractClientStreamTest.java @@ -56,7 +56,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; @@ -75,7 +74,6 @@ public class AbstractClientStreamTest { @Rule public final MockitoRule mocks = MockitoJUnit.rule(); - @Rule public final ExpectedException thrown = ExpectedException.none(); private final StatsTraceContext statsTraceCtx = StatsTraceContext.NOOP; private final TransportTracer transportTracer = new TransportTracer(); @@ -134,9 +132,11 @@ public void cancel_failsOnNull() { AbstractClientStream stream = new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer); stream.start(listener); - thrown.expect(NullPointerException.class); - - stream.cancel(null); + try { + stream.cancel(null); + fail(); + } catch (NullPointerException expected) { + } } @Test @@ -161,10 +161,11 @@ public void cancel(Status errorStatus) { public void startFailsOnNullListener() { AbstractClientStream stream = new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer); - - thrown.expect(NullPointerException.class); - - stream.start(null); + try { + stream.start(null); + fail(); + } catch (NullPointerException expected) { + } } @Test @@ -172,9 +173,11 @@ public void cantCallStartTwice() { AbstractClientStream stream = new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer); stream.start(mockListener); - thrown.expect(IllegalStateException.class); - - stream.start(mockListener); + try { + stream.start(mockListener); + fail(); + } catch (IllegalStateException expected) { + } } @Test @@ -186,8 +189,11 @@ public void inboundDataReceived_failsOnNullFrame() { TransportState state = stream.transportState(); - thrown.expect(NullPointerException.class); - state.inboundDataReceived(null); + try { + state.inboundDataReceived(null); + fail(); + } catch (NullPointerException expected) { + } } @Test @@ -210,8 +216,11 @@ public void inboundHeadersReceived_failsIfStatusReported() { TransportState state = stream.transportState(); - thrown.expect(IllegalStateException.class); - state.inboundHeadersReceived(new Metadata()); + try { + state.inboundHeadersReceived(new Metadata()); + fail(); + } catch (IllegalStateException expected) { + } } @Test diff --git a/core/src/test/java/io/grpc/internal/AbstractManagedChannelImplBuilderTest.java b/core/src/test/java/io/grpc/internal/AbstractManagedChannelImplBuilderTest.java index f7f79f0b5fe..0fdf9df2dac 100644 --- a/core/src/test/java/io/grpc/internal/AbstractManagedChannelImplBuilderTest.java +++ b/core/src/test/java/io/grpc/internal/AbstractManagedChannelImplBuilderTest.java @@ -45,9 +45,7 @@ import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -55,9 +53,6 @@ @RunWith(JUnit4.class) public class AbstractManagedChannelImplBuilderTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private static final ClientInterceptor DUMMY_USER_INTERCEPTOR = new ClientInterceptor() { @Override @@ -387,16 +382,22 @@ public void perRpcBufferLimit() { public void retryBufferSizeInvalidArg() { Builder builder = new Builder("target"); - thrown.expect(IllegalArgumentException.class); - builder.retryBufferSize(0L); + try { + builder.retryBufferSize(0L); + fail(); + } catch (IllegalArgumentException expected) { + } } @Test public void perRpcBufferLimitInvalidArg() { Builder builder = new Builder("target"); - thrown.expect(IllegalArgumentException.class); - builder.perRpcBufferLimit(0L); + try { + builder.perRpcBufferLimit(0L); + fail(); + } catch (IllegalArgumentException expected) { + } } @Test @@ -422,8 +423,11 @@ public void defaultServiceConfig_nullKey() { Map config = new HashMap<>(); config.put(null, "val"); - thrown.expect(IllegalArgumentException.class); - builder.defaultServiceConfig(config); + try { + builder.defaultServiceConfig(config); + fail(); + } catch (IllegalArgumentException expected) { + } } @Test @@ -434,8 +438,11 @@ public void defaultServiceConfig_intKey() { Map config = new HashMap<>(); config.put("key", subConfig); - thrown.expect(IllegalArgumentException.class); - builder.defaultServiceConfig(config); + try { + builder.defaultServiceConfig(config); + fail(); + } catch (IllegalArgumentException expected) { + } } @Test @@ -444,8 +451,11 @@ public void defaultServiceConfig_intValue() { Map config = new HashMap<>(); config.put("key", 3); - thrown.expect(IllegalArgumentException.class); - builder.defaultServiceConfig(config); + try { + builder.defaultServiceConfig(config); + fail(); + } catch (IllegalArgumentException expected) { + } } @Test diff --git a/core/src/test/java/io/grpc/internal/AbstractServerStreamTest.java b/core/src/test/java/io/grpc/internal/AbstractServerStreamTest.java index 1c572883b8c..0f6d61d1275 100644 --- a/core/src/test/java/io/grpc/internal/AbstractServerStreamTest.java +++ b/core/src/test/java/io/grpc/internal/AbstractServerStreamTest.java @@ -18,6 +18,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; import static org.mockito.AdditionalAnswers.delegatesTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -42,9 +43,7 @@ import java.util.Queue; import java.util.concurrent.TimeUnit; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; @@ -57,8 +56,6 @@ public class AbstractServerStreamTest { private static final int TIMEOUT_MS = 1000; private static final int MAX_MESSAGE_SIZE = 100; - @Rule public final ExpectedException thrown = ExpectedException.none(); - private final WritableBufferAllocator allocator = new WritableBufferAllocator() { @Override public WritableBuffer allocate(int capacityHint) { @@ -185,9 +182,12 @@ public void completeWithoutClose() { public void setListener_setOnlyOnce() { TransportState state = stream.transportState(); state.setListener(new ServerStreamListenerBase()); - thrown.expect(IllegalStateException.class); - state.setListener(new ServerStreamListenerBase()); + try { + state.setListener(new ServerStreamListenerBase()); + fail(); + } catch (IllegalStateException expected) { + } } @Test @@ -197,8 +197,11 @@ public void listenerReady_onlyOnce() { TransportState state = stream.transportState(); - thrown.expect(IllegalStateException.class); - state.onStreamAllocated(); + try { + state.onStreamAllocated(); + fail(); + } catch (IllegalStateException expected) { + } } @Test @@ -214,8 +217,11 @@ public void listenerReady_readyCalled() { public void setListener_failsOnNull() { TransportState state = stream.transportState(); - thrown.expect(NullPointerException.class); - state.setListener(null); + try { + state.setListener(null); + fail(); + } catch (NullPointerException expected) { + } } // TODO(ericgribkoff) This test is only valid if deframeInTransportThread=true, as otherwise the @@ -243,9 +249,11 @@ public void messagesAvailable(MessageProducer producer) { @Test public void writeHeaders_failsOnNullHeaders() { - thrown.expect(NullPointerException.class); - - stream.writeHeaders(null); + try { + stream.writeHeaders(null); + fail(); + } catch (NullPointerException expected) { + } } @Test @@ -295,16 +303,21 @@ public void writeMessage_closesStream() throws Exception { @Test public void close_failsOnNullStatus() { - thrown.expect(NullPointerException.class); - - stream.close(null, new Metadata()); + try { + stream.close(null, new Metadata()); + fail(); + } catch (NullPointerException expected) { + } } @Test public void close_failsOnNullMetadata() { - thrown.expect(NullPointerException.class); + try { + stream.close(Status.INTERNAL, null); + fail(); + } catch (NullPointerException expected) { + } - stream.close(Status.INTERNAL, null); } @Test diff --git a/core/src/test/java/io/grpc/internal/AbstractTransportTest.java b/core/src/test/java/io/grpc/internal/AbstractTransportTest.java index cca994c105a..5f721cc486e 100644 --- a/core/src/test/java/io/grpc/internal/AbstractTransportTest.java +++ b/core/src/test/java/io/grpc/internal/AbstractTransportTest.java @@ -77,9 +77,7 @@ import java.util.concurrent.TimeoutException; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; @@ -218,9 +216,6 @@ public ServerStreamTracer newServerStreamTracer(String fullMethodName, Metadata } })); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Before public void setUp() { server = Iterables.getOnlyElement(newServer(Arrays.asList(serverStreamTracerFactory))); @@ -396,8 +391,11 @@ public void serverAlreadyListening() throws Exception { } InternalServer server2 = Iterables.getOnlyElement(newServer(port, Arrays.asList(serverStreamTracerFactory))); - thrown.expect(IOException.class); - server2.start(new MockServerListener()); + try { + server2.start(new MockServerListener()); + fail(); + } catch (IOException expected) { + } } @Test diff --git a/core/src/test/java/io/grpc/internal/ConnectivityStateManagerTest.java b/core/src/test/java/io/grpc/internal/ConnectivityStateManagerTest.java index e12f9bf16cb..ac1861a8f8f 100644 --- a/core/src/test/java/io/grpc/internal/ConnectivityStateManagerTest.java +++ b/core/src/test/java/io/grpc/internal/ConnectivityStateManagerTest.java @@ -27,9 +27,7 @@ import io.grpc.ConnectivityState; import java.util.LinkedList; import java.util.concurrent.Executor; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -38,8 +36,6 @@ */ @RunWith(JUnit4.class) public class ConnectivityStateManagerTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); private final FakeClock executor = new FakeClock(); private final ConnectivityStateManager state = new ConnectivityStateManager(); diff --git a/core/src/test/java/io/grpc/internal/DnsNameResolverTest.java b/core/src/test/java/io/grpc/internal/DnsNameResolverTest.java index 09d1df69216..c0c1c39e6fe 100644 --- a/core/src/test/java/io/grpc/internal/DnsNameResolverTest.java +++ b/core/src/test/java/io/grpc/internal/DnsNameResolverTest.java @@ -81,7 +81,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; -import org.junit.rules.ExpectedException; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.junit.runner.RunWith; @@ -98,7 +97,6 @@ public class DnsNameResolverTest { @Rule public final TestRule globalTimeout = new DisableOnDebug(Timeout.seconds(10)); @Rule public final MockitoRule mocks = MockitoJUnit.rule(); - @Rule public final ExpectedException thrown = ExpectedException.none(); private final Map serviceConfig = new LinkedHashMap<>(); @@ -782,9 +780,13 @@ public HttpConnectProxiedSocketAddress proxyFor(SocketAddress targetAddress) { public void maybeChooseServiceConfig_failsOnMisspelling() { Map bad = new LinkedHashMap<>(); bad.put("parcentage", 1.0); - thrown.expectMessage("Bad key"); - DnsNameResolver.maybeChooseServiceConfig(bad, new Random(), "host"); + try { + DnsNameResolver.maybeChooseServiceConfig(bad, new Random(), "host"); + fail(); + } catch (Exception ex) { + assertTrue(ex.getMessage().contains("Bad key")); + } } @Test @@ -1028,9 +1030,12 @@ public void parseTxtResults_badTypeFails() throws Exception { txtRecords.add("some_record"); txtRecords.add("grpc_config={}"); - thrown.expect(ClassCastException.class); - thrown.expectMessage("wrong type"); - DnsNameResolver.parseTxtResults(txtRecords); + try { + DnsNameResolver.parseTxtResults(txtRecords); + fail(); + } catch (ClassCastException ex) { + assertTrue(ex.getMessage().contains("wrong type")); + } } @Test @@ -1039,9 +1044,12 @@ public void parseTxtResults_badInnerTypeFails() throws Exception { txtRecords.add("some_record"); txtRecords.add("grpc_config=[\"bogus\"]"); - thrown.expect(ClassCastException.class); - thrown.expectMessage("not object"); - DnsNameResolver.parseTxtResults(txtRecords); + try { + DnsNameResolver.parseTxtResults(txtRecords); + fail(); + } catch (ClassCastException ex) { + assertTrue(ex.getMessage().contains("not object")); + } } @Test diff --git a/core/src/test/java/io/grpc/internal/GrpcUtilTest.java b/core/src/test/java/io/grpc/internal/GrpcUtilTest.java index 30573f396d7..f92d4596126 100644 --- a/core/src/test/java/io/grpc/internal/GrpcUtilTest.java +++ b/core/src/test/java/io/grpc/internal/GrpcUtilTest.java @@ -22,6 +22,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -34,9 +35,7 @@ import io.grpc.internal.ClientStreamListener.RpcProgress; import io.grpc.internal.GrpcUtil.Http2Error; import io.grpc.testing.TestMethodDescriptors; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -44,8 +43,6 @@ @RunWith(JUnit4.class) public class GrpcUtilTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Test public void http2ErrorForCode() { // Try edge cases manually, to make the test obviously correct for important cases. @@ -146,9 +143,11 @@ public void contentTypeShouldNotBeValid() { @Test public void checkAuthority_failsOnNull() { - thrown.expect(NullPointerException.class); - - GrpcUtil.checkAuthority(null); + try { + GrpcUtil.checkAuthority(null); + fail(); + } catch (NullPointerException expected) { + } } @Test @@ -174,26 +173,32 @@ public void checkAuthority_succeedsOnIpV6() { @Test public void checkAuthority_failsOnInvalidAuthority() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid authority"); - - GrpcUtil.checkAuthority("[ : : 1]"); + try { + GrpcUtil.checkAuthority("[ : : 1]"); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("Invalid authority")); + } } @Test public void checkAuthority_failsOnInvalidHost() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("No host in authority"); - - GrpcUtil.checkAuthority("bad_host"); + try { + GrpcUtil.checkAuthority("bad_host"); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("No host in authority")); + } } @Test public void checkAuthority_userInfoNotAllowed() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Userinfo"); - - GrpcUtil.checkAuthority("foo@valid"); + try { + GrpcUtil.checkAuthority("foo@valid"); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("Userinfo")); + } } @Test diff --git a/core/src/test/java/io/grpc/internal/InternalSubchannelTest.java b/core/src/test/java/io/grpc/internal/InternalSubchannelTest.java index 37099995835..d3db2e2226d 100644 --- a/core/src/test/java/io/grpc/internal/InternalSubchannelTest.java +++ b/core/src/test/java/io/grpc/internal/InternalSubchannelTest.java @@ -28,6 +28,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; @@ -63,7 +64,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; @@ -77,8 +77,6 @@ public class InternalSubchannelTest { @Rule public final MockitoRule mocks = MockitoJUnit.rule(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); private static final String AUTHORITY = "fakeauthority"; private static final String USER_AGENT = "mosaic"; @@ -494,8 +492,12 @@ public void constructor_eagListWithNull_throws() { public void updateAddresses_emptyEagList_throws() { SocketAddress addr = new FakeSocketAddress(); createInternalSubchannel(addr); - thrown.expect(IllegalArgumentException.class); - internalSubchannel.updateAddresses(Arrays.asList()); + + try { + internalSubchannel.updateAddresses(Arrays.asList()); + fail(); + } catch (IllegalArgumentException expected) { + } } @Test @@ -503,8 +505,12 @@ public void updateAddresses_eagListWithNull_throws() { SocketAddress addr = new FakeSocketAddress(); createInternalSubchannel(addr); List eags = Arrays.asList((EquivalentAddressGroup) null); - thrown.expect(NullPointerException.class); - internalSubchannel.updateAddresses(eags); + + try { + internalSubchannel.updateAddresses(eags); + fail(); + } catch (NullPointerException expected) { + } } @Test public void updateAddresses_intersecting_ready() { diff --git a/core/src/test/java/io/grpc/internal/JsonParserTest.java b/core/src/test/java/io/grpc/internal/JsonParserTest.java index d783a650590..5095abe95c4 100644 --- a/core/src/test/java/io/grpc/internal/JsonParserTest.java +++ b/core/src/test/java/io/grpc/internal/JsonParserTest.java @@ -17,15 +17,14 @@ package io.grpc.internal; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import com.google.gson.stream.MalformedJsonException; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -35,9 +34,6 @@ @RunWith(JUnit4.class) public class JsonParserTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void emptyObject() throws IOException { assertEquals(new LinkedHashMap(), JsonParser.parse("{}")); @@ -75,44 +71,56 @@ public void nullValue() throws IOException { @Test public void nanFails() throws IOException { - thrown.expect(MalformedJsonException.class); - - JsonParser.parse("NaN"); + try { + JsonParser.parse("NaN"); + fail(); + } catch (MalformedJsonException expected) { + } } @Test public void objectEarlyEnd() throws IOException { - thrown.expect(MalformedJsonException.class); - - JsonParser.parse("{foo:}"); + try { + JsonParser.parse("{foo:}"); + fail(); + } catch (MalformedJsonException expected) { + } } @Test public void earlyEndArray() throws IOException { - thrown.expect(EOFException.class); - - JsonParser.parse("[1, 2, "); + try { + JsonParser.parse("[1, 2, "); + fail(); + } catch (EOFException expected) { + } } @Test public void arrayMissingElement() throws IOException { - thrown.expect(MalformedJsonException.class); - - JsonParser.parse("[1, 2, ]"); + try { + JsonParser.parse("[1, 2, ]"); + fail(); + } catch (MalformedJsonException expected) { + } } @Test public void objectMissingElement() throws IOException { - thrown.expect(MalformedJsonException.class); - - JsonParser.parse("{1: "); + try { + JsonParser.parse("{1: "); + fail(); + } catch (MalformedJsonException expected) { + } } @Test public void objectNoName() throws IOException { - thrown.expect(MalformedJsonException.class); - - JsonParser.parse("{: 1"); + try { + JsonParser.parse("{: 1"); + fail(); + } catch (MalformedJsonException expected) { + } } @Test diff --git a/core/src/test/java/io/grpc/internal/ManagedChannelServiceConfigTest.java b/core/src/test/java/io/grpc/internal/ManagedChannelServiceConfigTest.java index 5a7bad5a1b7..5817a030f12 100644 --- a/core/src/test/java/io/grpc/internal/ManagedChannelServiceConfigTest.java +++ b/core/src/test/java/io/grpc/internal/ManagedChannelServiceConfigTest.java @@ -17,23 +17,20 @@ package io.grpc.internal; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ManagedChannelServiceConfigTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void managedChannelServiceConfig_shouldParseHealthCheckingConfig() throws Exception { Map rawServiceConfig = @@ -66,10 +63,12 @@ public void createManagedChannelServiceConfig_failsOnDuplicateMethod() { Map methodConfig = ImmutableMap.of("name", ImmutableList.of(name1, name2)); Map serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Duplicate method"); - - ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + try { + ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("Duplicate method name service/method", ex.getMessage()); + } } @Test @@ -79,10 +78,12 @@ public void createManagedChannelServiceConfig_failsOnDuplicateService() { Map methodConfig = ImmutableMap.of("name", ImmutableList.of(name1, name2)); Map serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Duplicate service"); - - ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + try { + ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("Duplicate service service", ex.getMessage()); + } } @Test @@ -94,10 +95,12 @@ public void createManagedChannelServiceConfig_failsOnDuplicateServiceMultipleCon Map serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig1, methodConfig2)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Duplicate service"); - - ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + try { + ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("Duplicate service service", ex.getMessage()); + } } @Test @@ -106,10 +109,12 @@ public void createManagedChannelServiceConfig_failsOnMethodNameWithEmptyServiceN Map methodConfig = ImmutableMap.of("name", ImmutableList.of(name)); Map serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("missing service name for method method1"); - - ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + try { + ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("missing service name for method method1", ex.getMessage()); + } } @Test @@ -118,10 +123,12 @@ public void createManagedChannelServiceConfig_failsOnMethodNameWithoutServiceNam Map methodConfig = ImmutableMap.of("name", ImmutableList.of(name)); Map serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("missing service name for method method1"); - - ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + try { + ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("missing service name for method method1", ex.getMessage()); + } } @Test @@ -130,12 +137,15 @@ public void createManagedChannelServiceConfig_failsOnMissingServiceName() { Map methodConfig = ImmutableMap.of("name", ImmutableList.of(name)); Map serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("missing service"); - - ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + try { + ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("missing service name for method method", ex.getMessage()); + } } + @SuppressWarnings("unchecked") private static Map parseConfig(String json) throws Exception { return (Map) JsonParser.parse(json); diff --git a/core/src/test/java/io/grpc/internal/MessageDeframerTest.java b/core/src/test/java/io/grpc/internal/MessageDeframerTest.java index 961e51771b8..f03a7854109 100644 --- a/core/src/test/java/io/grpc/internal/MessageDeframerTest.java +++ b/core/src/test/java/io/grpc/internal/MessageDeframerTest.java @@ -51,11 +51,10 @@ import java.util.List; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; +import org.junit.Assert; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; import org.junit.experimental.runners.Enclosed; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.runners.Parameterized; @@ -337,8 +336,6 @@ public Void answer(InvocationOnMock invocation) throws Throwable { @RunWith(JUnit4.class) public static class SizeEnforcingInputStreamTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); private TestBaseStreamTracer tracer = new TestBaseStreamTracer(); private StatsTraceContext statsTraceCtx = new StatsTraceContext(new StreamTracer[]{tracer}); @@ -373,14 +370,14 @@ public void sizeEnforcingInputStream_readByteAtLimit() throws IOException { public void sizeEnforcingInputStream_readByteAboveLimit() throws IOException { ByteArrayInputStream in = new ByteArrayInputStream("foo".getBytes(Charsets.UTF_8)); SizeEnforcingInputStream stream = - new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx); - + new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx); try { - thrown.expect(StatusRuntimeException.class); - thrown.expectMessage("RESOURCE_EXHAUSTED: Compressed gRPC message exceeds"); - while (stream.read() != -1) { } + Assert.fail(); + } catch (StatusRuntimeException ex) { + assertTrue( + ex.getMessage().startsWith("RESOURCE_EXHAUSTED: Compressed gRPC message exceeds")); } finally { stream.close(); } @@ -417,15 +414,15 @@ public void sizeEnforcingInputStream_readAtLimit() throws IOException { @Test public void sizeEnforcingInputStream_readAboveLimit() throws IOException { ByteArrayInputStream in = new ByteArrayInputStream("foo".getBytes(Charsets.UTF_8)); - SizeEnforcingInputStream stream = - new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx); byte[] buf = new byte[10]; - + SizeEnforcingInputStream stream = + new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx); try { - thrown.expect(StatusRuntimeException.class); - thrown.expectMessage("RESOURCE_EXHAUSTED: Compressed gRPC message exceeds"); - stream.read(buf, 0, buf.length); + Assert.fail(); + } catch (StatusRuntimeException ex) { + assertTrue( + ex.getMessage().startsWith("RESOURCE_EXHAUSTED: Compressed gRPC message exceeds")); } finally { stream.close(); } @@ -462,13 +459,13 @@ public void sizeEnforcingInputStream_skipAtLimit() throws IOException { public void sizeEnforcingInputStream_skipAboveLimit() throws IOException { ByteArrayInputStream in = new ByteArrayInputStream("foo".getBytes(Charsets.UTF_8)); SizeEnforcingInputStream stream = - new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx); - + new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx); try { - thrown.expect(StatusRuntimeException.class); - thrown.expectMessage("RESOURCE_EXHAUSTED: Compressed gRPC message exceeds"); - stream.skip(4); + Assert.fail(); + } catch (StatusRuntimeException ex) { + assertTrue( + ex.getMessage().startsWith("RESOURCE_EXHAUSTED: Compressed gRPC message exceeds")); } finally { stream.close(); } diff --git a/core/src/test/java/io/grpc/internal/ServerCallImplTest.java b/core/src/test/java/io/grpc/internal/ServerCallImplTest.java index a4c0da2d69d..7a62e98008f 100644 --- a/core/src/test/java/io/grpc/internal/ServerCallImplTest.java +++ b/core/src/test/java/io/grpc/internal/ServerCallImplTest.java @@ -48,9 +48,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; @@ -59,7 +57,6 @@ @RunWith(JUnit4.class) public class ServerCallImplTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); @Mock private ServerStream stream; @Mock private ServerCall.Listener callListener; @@ -152,20 +149,25 @@ public void sendHeader_firstCall() { @Test public void sendHeader_failsOnSecondCall() { call.sendHeaders(new Metadata()); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("sendHeaders has already been called"); - call.sendHeaders(new Metadata()); + try { + call.sendHeaders(new Metadata()); + fail(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().contains("sendHeaders has already been called")); + } } @Test public void sendHeader_failsOnClosed() { call.close(Status.CANCELLED, new Metadata()); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("call is closed"); - - call.sendHeaders(new Metadata()); + try { + call.sendHeaders(new Metadata()); + fail(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().contains("call is closed")); + } } @Test @@ -182,18 +184,22 @@ public void sendMessage_failsOnClosed() { call.sendHeaders(new Metadata()); call.close(Status.CANCELLED, new Metadata()); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("call is closed"); - - call.sendMessage(1234L); + try { + call.sendMessage(1234L); + fail(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().contains("call is closed")); + } } @Test public void sendMessage_failsIfheadersUnsent() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("sendHeaders has not been called"); - - call.sendMessage(1234L); + try { + call.sendMessage(1234L); + fail(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().contains("sendHeaders has not been called")); + } } @Test @@ -446,9 +452,12 @@ public void streamListener_unexpectedRuntimeException() { InputStream inputStream = UNARY_METHOD.streamRequest(1234L); - thrown.expect(RuntimeException.class); - thrown.expectMessage("unexpected exception"); - streamListener.messagesAvailable(new SingleMessageProducer(inputStream)); + try { + streamListener.messagesAvailable(new SingleMessageProducer(inputStream)); + fail(); + } catch (RuntimeException ex) { + assertTrue(ex.getMessage().contains("unexpected exception")); + } } private static class LongMarshaller implements Marshaller { diff --git a/core/src/test/java/io/grpc/internal/ServerImplTest.java b/core/src/test/java/io/grpc/internal/ServerImplTest.java index b32833f3439..c20d3eab728 100644 --- a/core/src/test/java/io/grpc/internal/ServerImplTest.java +++ b/core/src/test/java/io/grpc/internal/ServerImplTest.java @@ -102,9 +102,7 @@ import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; @@ -139,8 +137,6 @@ public boolean shouldAccept(Runnable runnable) { }; private static final String AUTHORITY = "some_authority"; - @Rule public final ExpectedException thrown = ExpectedException.none(); - @BeforeClass public static void beforeStartUp() { // Cancel the root context. Server will fork it so the per-call context should not @@ -1137,9 +1133,14 @@ public SocketAddress getListenSocketAddress() { public void getPortBeforeStartedFails() { transportServer = new SimpleServer(); createServer(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("started"); - server.getPort(); + + try { + server.getPort(); + fail(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().contains("started")); + } + } @Test @@ -1148,9 +1149,13 @@ public void getPortAfterTerminationFails() throws Exception { createAndStartServer(); server.shutdown(); server.awaitTermination(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("terminated"); - server.getPort(); + + try { + server.getPort(); + fail(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().contains("terminated")); + } } @Test diff --git a/core/src/test/java/io/grpc/internal/ServiceConfigInterceptorTest.java b/core/src/test/java/io/grpc/internal/ServiceConfigInterceptorTest.java index eaa67480318..79691ba2c83 100644 --- a/core/src/test/java/io/grpc/internal/ServiceConfigInterceptorTest.java +++ b/core/src/test/java/io/grpc/internal/ServiceConfigInterceptorTest.java @@ -19,6 +19,8 @@ import static com.google.common.truth.Truth.assertThat; import static io.grpc.internal.ServiceConfigInterceptor.HEDGING_POLICY_KEY; import static io.grpc.internal.ServiceConfigInterceptor.RETRY_POLICY_KEY; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; @@ -34,9 +36,7 @@ import java.util.HashMap; import java.util.concurrent.TimeUnit; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; @@ -50,8 +50,6 @@ @RunWith(JUnit4.class) public class ServiceConfigInterceptorTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Mock private Channel channel; @Captor private ArgumentCaptor callOptionsCap; @@ -465,9 +463,12 @@ public void methodInfo_validateDeadline() { JsonObj name = new JsonObj("service", "service"); JsonObj methodConfig = new JsonObj("name", new JsonList(name), "timeout", "10000000000000000s"); - thrown.expectMessage("Duration value is out of range"); - - new MethodInfo(methodConfig, false, 1, 1); + try { + new MethodInfo(methodConfig, false, 1, 1); + fail(); + } catch (RuntimeException ex) { + assertTrue(ex.getMessage().contains("Duration value is out of range")); + } } @Test @@ -485,10 +486,12 @@ public void methodInfo_badMaxRequestSize() { JsonObj name = new JsonObj("service", "service"); JsonObj methodConfig = new JsonObj("name", new JsonList(name), "maxRequestMessageBytes", -1d); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("exceeds bounds"); - - new MethodInfo(methodConfig, false, 1, 1); + try { + new MethodInfo(methodConfig, false, 1, 1); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("exceeds bounds")); + } } @Test @@ -496,10 +499,12 @@ public void methodInfo_badMaxResponseSize() { JsonObj name = new JsonObj("service", "service"); JsonObj methodConfig = new JsonObj("name", new JsonList(name), "maxResponseMessageBytes", -1d); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("exceeds bounds"); - - new MethodInfo(methodConfig, false, 1, 1); + try { + new MethodInfo(methodConfig, false, 1, 1); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("exceeds bounds")); + } } private static ManagedChannelServiceConfig createManagedChannelServiceConfig( diff --git a/core/src/test/java/io/grpc/util/GracefulSwitchLoadBalancerTest.java b/core/src/test/java/io/grpc/util/GracefulSwitchLoadBalancerTest.java index f55d93c2057..d935399cd8f 100644 --- a/core/src/test/java/io/grpc/util/GracefulSwitchLoadBalancerTest.java +++ b/core/src/test/java/io/grpc/util/GracefulSwitchLoadBalancerTest.java @@ -21,6 +21,7 @@ import static io.grpc.ConnectivityState.READY; import static io.grpc.ConnectivityState.TRANSIENT_FAILURE; import static io.grpc.util.GracefulSwitchLoadBalancer.BUFFER_PICKER; +import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.inOrder; @@ -49,9 +50,7 @@ import java.util.List; import java.util.Map; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; @@ -62,8 +61,6 @@ */ @RunWith(JUnit4.class) public class GracefulSwitchLoadBalancerTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); private final LoadBalancerRegistry lbRegistry = new LoadBalancerRegistry(); // maps policy name to lb provide @@ -491,8 +488,12 @@ public void handleSubchannelState_shouldThrow() { gracefulSwitchLb.switchTo(lbProviders.get(lbPolicies[0])); Subchannel subchannel = mock(Subchannel.class); ConnectivityStateInfo connectivityStateInfo = ConnectivityStateInfo.forNonError(READY); - thrown.expect(UnsupportedOperationException.class); - gracefulSwitchLb.handleSubchannelState(subchannel, connectivityStateInfo); + + try { + gracefulSwitchLb.handleSubchannelState(subchannel, connectivityStateInfo); + fail(); + } catch (UnsupportedOperationException expected) { + } } private final class FakeLoadBalancerProvider extends LoadBalancerProvider { diff --git a/netty/src/test/java/io/grpc/netty/GrpcHttp2HeadersUtilsTest.java b/netty/src/test/java/io/grpc/netty/GrpcHttp2HeadersUtilsTest.java index 96d87a53789..9336035f897 100644 --- a/netty/src/test/java/io/grpc/netty/GrpcHttp2HeadersUtilsTest.java +++ b/netty/src/test/java/io/grpc/netty/GrpcHttp2HeadersUtilsTest.java @@ -20,8 +20,8 @@ import static io.grpc.internal.GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE; import static io.netty.util.AsciiString.of; import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.common.collect.Iterables; diff --git a/netty/src/test/java/io/grpc/netty/NettyChannelBuilderTest.java b/netty/src/test/java/io/grpc/netty/NettyChannelBuilderTest.java index 3621e6e2454..f8d8cfcb47c 100644 --- a/netty/src/test/java/io/grpc/netty/NettyChannelBuilderTest.java +++ b/netty/src/test/java/io/grpc/netty/NettyChannelBuilderTest.java @@ -19,6 +19,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import io.grpc.ManagedChannel; @@ -33,16 +34,13 @@ import java.net.SocketAddress; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class NettyChannelBuilderTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); private final SslContext noSslContext = null; private void shutdown(ManagedChannel mc) throws Exception { @@ -109,19 +107,22 @@ public String checkAuthority(String authority) { public void failOverrideInvalidAuthority() { NettyChannelBuilder builder = new NettyChannelBuilder(new SocketAddress(){}); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid authority:"); - - builder.overrideAuthority("[invalidauthority"); + try { + builder.overrideAuthority("[invalidauthority"); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("[invalidauthority")); + } } @Test public void failInvalidAuthority() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid host or port"); - - Object unused = - NettyChannelBuilder.forAddress(new InetSocketAddress("invalid_authority", 1234)); + try { + NettyChannelBuilder.forAddress(new InetSocketAddress("invalid_authority", 1234)); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("Invalid host or port")); + } } @Test @@ -135,10 +136,12 @@ public void failIfSslContextIsNotClient() { SslContext sslContext = mock(SslContext.class); NettyChannelBuilder builder = new NettyChannelBuilder(new SocketAddress(){}); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Server SSL context can not be used for client channel"); - - builder.sslContext(sslContext); + try { + builder.sslContext(sslContext); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("Server SSL context can not be used for client channel")); + } } @Test @@ -163,10 +166,13 @@ public void createProtocolNegotiatorByType_plaintextUpgrade() { @Test public void createProtocolNegotiatorByType_tlsWithNoContext() { - thrown.expect(NullPointerException.class); - NettyChannelBuilder.createProtocolNegotiatorByType( - NegotiationType.TLS, - noSslContext, null); + try { + NettyChannelBuilder.createProtocolNegotiatorByType( + NegotiationType.TLS, + noSslContext, null); + fail(); + } catch (NullPointerException expected) { + } } @Test @@ -203,38 +209,52 @@ public void createProtocolNegotiatorByType_tlsWithAuthorityFallback() throws SSL public void negativeKeepAliveTime() { NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("keepalive time must be positive"); - builder.keepAliveTime(-1L, TimeUnit.HOURS); + try { + builder.keepAliveTime(-1L, TimeUnit.HOURS); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("keepalive time must be positive")); + } } @Test public void negativeKeepAliveTimeout() { NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("keepalive timeout must be positive"); - builder.keepAliveTimeout(-1L, TimeUnit.HOURS); + try { + builder.keepAliveTimeout(-1L, TimeUnit.HOURS); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().contains("keepalive timeout must be positive")); + } } @Test public void assertEventLoopAndChannelType_onlyGroupProvided() { NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget"); builder.eventLoopGroup(mock(EventLoopGroup.class)); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Both EventLoopGroup and ChannelType should be provided"); - builder.assertEventLoopAndChannelType(); + try { + builder.assertEventLoopAndChannelType(); + fail(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().contains( + "Both EventLoopGroup and ChannelType should be provided")); + } } @Test public void assertEventLoopAndChannelType_onlyTypeProvided() { NettyChannelBuilder builder = NettyChannelBuilder.forTarget("fakeTarget"); builder.channelType(LocalChannel.class); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Both EventLoopGroup and ChannelType should be provided"); - builder.assertEventLoopAndChannelType(); + try { + builder.assertEventLoopAndChannelType(); + fail(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().contains( + "Both EventLoopGroup and ChannelType should be provided")); + } } @Test @@ -246,10 +266,14 @@ public Channel newChannel() { return null; } }); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Both EventLoopGroup and ChannelType should be provided"); - builder.assertEventLoopAndChannelType(); + try { + builder.assertEventLoopAndChannelType(); + fail(); + } catch (IllegalStateException ex) { + assertTrue(ex.getMessage().contains( + "Both EventLoopGroup and ChannelType should be provided")); + } } @Test diff --git a/netty/src/test/java/io/grpc/netty/NettyServerBuilderTest.java b/netty/src/test/java/io/grpc/netty/NettyServerBuilderTest.java index dfbfa3fa746..c6092988937 100644 --- a/netty/src/test/java/io/grpc/netty/NettyServerBuilderTest.java +++ b/netty/src/test/java/io/grpc/netty/NettyServerBuilderTest.java @@ -16,6 +16,9 @@ package io.grpc.netty; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -28,9 +31,7 @@ import java.net.InetSocketAddress; import java.util.List; import java.util.concurrent.TimeUnit; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -40,8 +41,6 @@ @RunWith(JUnit4.class) public class NettyServerBuilderTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - private NettyServerBuilder builder = NettyServerBuilder.forPort(8080); @Test @@ -62,105 +61,139 @@ public void failIfSslContextIsNotServer() { SslContext sslContext = mock(SslContext.class); when(sslContext.isClient()).thenReturn(true); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Client SSL context can not be used for server"); - builder.sslContext(sslContext); + try { + builder.sslContext(sslContext); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("Client SSL context can not be used for server", ex.getMessage()); + } + } @Test public void failIfKeepAliveTimeNegative() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("keepalive time must be positive"); - builder.keepAliveTime(-10L, TimeUnit.HOURS); + try { + builder.keepAliveTime(-10L, TimeUnit.HOURS); + fail(); + } catch (IllegalArgumentException ex) { + assertTrue(ex.getMessage().startsWith("keepalive time must be positive")); + } } @Test public void failIfKeepAliveTimeoutNegative() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("keepalive timeout must be positive"); - - builder.keepAliveTimeout(-10L, TimeUnit.HOURS); + try { + builder.keepAliveTimeout(-10L, TimeUnit.HOURS); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("keepalive timeout must be positive: -10", ex.getMessage()); + } } @Test public void failIfMaxConcurrentCallsPerConnectionNegative() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("max must be positive"); - - builder.maxConcurrentCallsPerConnection(0); + try { + builder.maxConcurrentCallsPerConnection(0); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("max must be positive: 0", ex.getMessage()); + } } @Test public void failIfMaxInboundMetadataSizeNonPositive() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("maxInboundMetadataSize must be positive"); - - builder.maxInboundMetadataSize(0); + try { + builder.maxInboundMetadataSize(0); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("maxInboundMetadataSize must be positive: 0", ex.getMessage()); + } } @Test public void failIfMaxConnectionIdleNegative() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("max connection idle must be positive"); - - builder.maxConnectionIdle(-1, TimeUnit.HOURS); + try { + builder.maxConnectionIdle(-1, TimeUnit.HOURS); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("max connection idle must be positive: -1", ex.getMessage()); + } } @Test public void failIfMaxConnectionAgeNegative() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("max connection age must be positive"); - - builder.maxConnectionAge(-1, TimeUnit.HOURS); + try { + builder.maxConnectionAge(-1, TimeUnit.HOURS); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("max connection age must be positive: -1", ex.getMessage()); + } } @Test public void failIfMaxConnectionAgeGraceNegative() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("max connection age grace must be non-negative"); - - builder.maxConnectionAgeGrace(-1, TimeUnit.HOURS); + try { + builder.maxConnectionAgeGrace(-1, TimeUnit.HOURS); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("max connection age grace must be non-negative: -1", ex.getMessage()); + } } @Test public void failIfPermitKeepAliveTimeNegative() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("permit keepalive time must be non-negative"); - - builder.permitKeepAliveTime(-1, TimeUnit.HOURS); + try { + builder.permitKeepAliveTime(-1, TimeUnit.HOURS); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("permit keepalive time must be non-negative: -1", ex.getMessage()); + } } @Test public void assertEventLoopsAndChannelType_onlyBossGroupProvided() { EventLoopGroup mockEventLoopGroup = mock(EventLoopGroup.class); builder.bossEventLoopGroup(mockEventLoopGroup); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be provided"); - builder.assertEventLoopsAndChannelType(); + try { + builder.assertEventLoopsAndChannelType(); + fail(); + } catch (IllegalStateException ex) { + assertEquals( + "All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be " + + "provided or neither should be", + ex.getMessage()); + } } @Test public void assertEventLoopsAndChannelType_onlyWorkerGroupProvided() { EventLoopGroup mockEventLoopGroup = mock(EventLoopGroup.class); builder.workerEventLoopGroup(mockEventLoopGroup); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be provided"); - - builder.assertEventLoopsAndChannelType(); + try { + builder.assertEventLoopsAndChannelType(); + fail(); + } catch (IllegalStateException ex) { + assertEquals( + "All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be " + + "provided or neither should be", + ex.getMessage()); + } } @Test public void assertEventLoopsAndChannelType_onlyTypeProvided() { builder.channelType(LocalServerChannel.class); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be provided"); - - builder.assertEventLoopsAndChannelType(); + try { + builder.assertEventLoopsAndChannelType(); + fail(); + } catch (IllegalStateException ex) { + assertEquals( + "All of BossEventLoopGroup, WorkerEventLoopGroup and ChannelType should be " + + "provided or neither should be", + ex.getMessage()); + } } @Test diff --git a/netty/src/test/java/io/grpc/netty/ProtocolNegotiatorsTest.java b/netty/src/test/java/io/grpc/netty/ProtocolNegotiatorsTest.java index 92b95eefa25..90e3728ad85 100644 --- a/netty/src/test/java/io/grpc/netty/ProtocolNegotiatorsTest.java +++ b/netty/src/test/java/io/grpc/netty/ProtocolNegotiatorsTest.java @@ -25,6 +25,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -76,7 +77,6 @@ import io.netty.handler.codec.http2.Http2ConnectionEncoder; import io.netty.handler.codec.http2.Http2ServerUpgradeCodec; import io.netty.handler.codec.http2.Http2Settings; -import io.netty.handler.proxy.ProxyConnectException; import io.netty.handler.ssl.ApplicationProtocolConfig; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; @@ -105,7 +105,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; -import org.junit.rules.ExpectedException; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.junit.runner.RunWith; @@ -122,7 +121,6 @@ public class ProtocolNegotiatorsTest { private static final int TIMEOUT_SECONDS = 60; @Rule public final TestRule globalTimeout = new DisableOnDebug(Timeout.seconds(TIMEOUT_SECONDS)); - @Rule public final ExpectedException thrown = ExpectedException.none(); private final EventLoopGroup group = new DefaultEventLoop(); private Channel chan; @@ -240,16 +238,18 @@ public void handlerAdded(ChannelHandlerContext ctx) throws Exception { } @Test - public void tlsHandler_failsOnNullEngine() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("ssl"); - - Object unused = ProtocolNegotiators.serverTls(null); + public void tlsHandler_failsOnNullEngine() { + try { + Object unused = ProtocolNegotiators.serverTls(null); + fail(); + } catch (NullPointerException expected) { + assertTrue(expected.getMessage().contains("ssl")); + } } @Test - public void tlsHandler_handlerAddedAddsSslHandler() throws Exception { + public void tlsHandler_handlerAddedAddsSslHandler() { ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext, null); pipeline.addLast(handler); @@ -559,9 +559,11 @@ public boolean isLoggable(LogRecord record) { @Test public void tls_failsOnNullSslContext() { - thrown.expect(NullPointerException.class); - - Object unused = ProtocolNegotiators.tls(null); + try { + Object unused = ProtocolNegotiators.tls(null); + fail(); + } catch (NullPointerException expected) { + } } @Test @@ -592,16 +594,23 @@ public void tls_invalidHost() throws SSLException { @Test public void httpProxy_nullAddressNpe() throws Exception { - thrown.expect(NullPointerException.class); - Object unused = - ProtocolNegotiators.httpProxy(null, "user", "pass", ProtocolNegotiators.plaintext()); + + try { + Object unused = + ProtocolNegotiators.httpProxy(null, "user", "pass", ProtocolNegotiators.plaintext()); + fail(); + } catch (NullPointerException expected) { + } } @Test - public void httpProxy_nullNegotiatorNpe() throws Exception { - thrown.expect(NullPointerException.class); - Object unused = ProtocolNegotiators.httpProxy( - InetSocketAddress.createUnresolved("localhost", 80), "user", "pass", null); + public void httpProxy_nullNegotiatorNpe() { + try { + ProtocolNegotiators.httpProxy(InetSocketAddress.createUnresolved("localhost", 80), + "user", "pass", null); + fail(); + } catch (NullPointerException expected) { + } } @Test @@ -719,9 +728,10 @@ public void httpProxy_500() throws Exception { assertFalse(negotiationFuture.isDone()); String response = "HTTP/1.1 500 OMG\r\nContent-Length: 4\r\n\r\noops"; serverContext.writeAndFlush(bb(response, serverContext.channel())).sync(); - thrown.expect(ProxyConnectException.class); try { negotiationFuture.sync(); + fail(); + } catch (Exception expected) { } finally { channel.close(); } diff --git a/okhttp/src/test/java/io/grpc/okhttp/UtilsTest.java b/okhttp/src/test/java/io/grpc/okhttp/UtilsTest.java index cdaf98c5736..a0bbc346603 100644 --- a/okhttp/src/test/java/io/grpc/okhttp/UtilsTest.java +++ b/okhttp/src/test/java/io/grpc/okhttp/UtilsTest.java @@ -18,6 +18,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import io.grpc.InternalChannelz.SocketOptions; import io.grpc.okhttp.internal.CipherSuite; @@ -25,9 +26,7 @@ import io.grpc.okhttp.internal.TlsVersion; import java.net.Socket; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -37,15 +36,15 @@ @RunWith(JUnit4.class) public class UtilsTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void convertSpecRejectsPlaintext() { com.squareup.okhttp.ConnectionSpec plaintext = com.squareup.okhttp.ConnectionSpec.CLEARTEXT; - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("plaintext ConnectionSpec is not accepted"); - Utils.convertSpec(plaintext); + try { + Utils.convertSpec(plaintext); + fail(); + } catch (IllegalArgumentException ex) { + assertEquals("plaintext ConnectionSpec is not accepted", ex.getMessage()); + } } @Test diff --git a/protobuf-lite/src/test/java/io/grpc/protobuf/lite/ProtoLiteUtilsTest.java b/protobuf-lite/src/test/java/io/grpc/protobuf/lite/ProtoLiteUtilsTest.java index d05e884105e..5aa84c7612f 100644 --- a/protobuf-lite/src/test/java/io/grpc/protobuf/lite/ProtoLiteUtilsTest.java +++ b/protobuf-lite/src/test/java/io/grpc/protobuf/lite/ProtoLiteUtilsTest.java @@ -20,6 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.io.ByteStreams; @@ -41,9 +42,7 @@ import java.io.IOException; import java.io.InputStream; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -51,8 +50,6 @@ @RunWith(JUnit4.class) public class ProtoLiteUtilsTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - private Marshaller marshaller = ProtoLiteUtils.marshaller(Type.getDefaultInstance()); private Type proto = Type.newBuilder().setName("name").build(); @@ -211,10 +208,12 @@ public void metadataMarshaller_invalid() { @Test public void extensionRegistry_notNull() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("newRegistry"); - - ProtoLiteUtils.setExtensionRegistry(null); + try { + ProtoLiteUtils.setExtensionRegistry(null); + fail(); + } catch (NullPointerException ex) { + assertTrue(ex.getMessage().contains("newRegistry")); + } } @Test diff --git a/xds/src/test/java/io/grpc/xds/BootstrapperTest.java b/xds/src/test/java/io/grpc/xds/BootstrapperTest.java index 37ef4161259..060769dcf84 100644 --- a/xds/src/test/java/io/grpc/xds/BootstrapperTest.java +++ b/xds/src/test/java/io/grpc/xds/BootstrapperTest.java @@ -29,9 +29,8 @@ import io.grpc.xds.Bootstrapper.ServerInfo; import java.io.IOException; import java.util.List; -import org.junit.Rule; +import org.junit.Assert; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -39,8 +38,6 @@ @RunWith(JUnit4.class) public class BootstrapperTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - @Test public void parseBootstrap_validData_singleXdsServer() throws IOException { String rawData = "{\n" @@ -218,8 +215,12 @@ public void parseBootstrap_IgnoreIrrelevantFields() throws IOException { public void parseBootstrap_emptyData() throws IOException { String rawData = ""; - thrown.expect(IOException.class); - Bootstrapper.parseConfig(rawData); + try { + Bootstrapper.parseConfig(rawData); + Assert.fail(); + } catch (IOException expected) { + } + } @Test @@ -269,9 +270,12 @@ public void parseBootstrap_noXdsServers() throws IOException { + " }\n" + "}"; - thrown.expect(IOException.class); - thrown.expectMessage("Invalid bootstrap: 'xds_servers' does not exist."); - Bootstrapper.parseConfig(rawData); + try { + Bootstrapper.parseConfig(rawData); + Assert.fail(); + } catch (IOException ex) { + Assert.assertEquals("Invalid bootstrap: 'xds_servers' does not exist.", ex.getMessage()); + } } @Test @@ -299,9 +303,13 @@ public void parseBootstrap_serverWithoutServerUri() throws IOException { + " ]\n " + "}"; - thrown.expect(IOException.class); - thrown.expectMessage("Invalid bootstrap: 'xds_servers' contains unknown server."); - Bootstrapper.parseConfig(rawData); + try { + Bootstrapper.parseConfig(rawData); + Assert.fail(); + } catch (IOException ex) { + Assert.assertEquals("Invalid bootstrap: 'xds_servers' contains unknown server.", + ex.getMessage()); + } } @SuppressWarnings("deprecation") diff --git a/xds/src/test/java/io/grpc/xds/WeightedRandomPickerTest.java b/xds/src/test/java/io/grpc/xds/WeightedRandomPickerTest.java index e88f9cbfbab..810129172c3 100644 --- a/xds/src/test/java/io/grpc/xds/WeightedRandomPickerTest.java +++ b/xds/src/test/java/io/grpc/xds/WeightedRandomPickerTest.java @@ -28,9 +28,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.junit.Assert; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; @@ -42,8 +42,6 @@ */ @RunWith(JUnit4.class) public class WeightedRandomPickerTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); @Rule public final MockitoRule mockitoRule = MockitoJUnit.rule(); @@ -104,14 +102,20 @@ public int nextInt(int bound) { public void emptyList() { List emptyList = new ArrayList<>(); - thrown.expect(IllegalArgumentException.class); - new WeightedRandomPicker(emptyList); + try { + new WeightedRandomPicker(emptyList); + Assert.fail(); + } catch (IllegalArgumentException expected) { + } } @Test public void negativeWeight() { - thrown.expect(IllegalArgumentException.class); - new WeightedChildPicker(-1, childPicker0); + try { + new WeightedChildPicker(-1, childPicker0); + Assert.fail(); + } catch (IllegalArgumentException expected) { + } } @Test diff --git a/xds/src/test/java/io/grpc/xds/XdsClientImplTest.java b/xds/src/test/java/io/grpc/xds/XdsClientImplTest.java index f67232f6240..31126d048c6 100644 --- a/xds/src/test/java/io/grpc/xds/XdsClientImplTest.java +++ b/xds/src/test/java/io/grpc/xds/XdsClientImplTest.java @@ -111,10 +111,10 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; @@ -179,8 +179,6 @@ public boolean shouldAccept(Runnable command) { @Rule public final GrpcCleanupRule cleanupRule = new GrpcCleanupRule(); - @Rule - public ExpectedException thrown = ExpectedException.none(); private final SynchronizationContext syncContext = new SynchronizationContext( new Thread.UncaughtExceptionHandler() { @@ -3441,8 +3439,11 @@ public void populateRoutesInVirtualHost_routeWithCaseInsensitiveMatch() { .setCaseSensitive(BoolValue.newBuilder().setValue(false)))) .build(); - thrown.expect(XdsClientImpl.InvalidProtoDataException.class); - XdsClientImpl.populateRoutesInVirtualHost(virtualHost); + try { + XdsClientImpl.populateRoutesInVirtualHost(virtualHost); + Assert.fail(); + } catch (XdsClientImpl.InvalidProtoDataException expected) { + } } @Test @@ -3460,8 +3461,11 @@ public void populateRoutesInVirtualHost_lastRouteIsNotDefaultRoute() { .setCaseSensitive(BoolValue.newBuilder().setValue(true)))) .build(); - thrown.expect(XdsClientImpl.InvalidProtoDataException.class); - XdsClientImpl.populateRoutesInVirtualHost(virtualHost); + try { + XdsClientImpl.populateRoutesInVirtualHost(virtualHost); + Assert.fail(); + } catch (XdsClientImpl.InvalidProtoDataException expected) { + } } @Test @@ -3485,8 +3489,11 @@ public void populateRoutesInVirtualHost_NoUsableRoute() { .addQueryParameters(QueryParameterMatcher.getDefaultInstance()))) .build(); - thrown.expect(XdsClientImpl.InvalidProtoDataException.class); - XdsClientImpl.populateRoutesInVirtualHost(virtualHost); + try { + XdsClientImpl.populateRoutesInVirtualHost(virtualHost); + Assert.fail(); + } catch (XdsClientImpl.InvalidProtoDataException expected) { + } } @Test diff --git a/xds/src/test/java/io/grpc/xds/XdsClientTest.java b/xds/src/test/java/io/grpc/xds/XdsClientTest.java index 56fca6dc09b..04311429353 100644 --- a/xds/src/test/java/io/grpc/xds/XdsClientTest.java +++ b/xds/src/test/java/io/grpc/xds/XdsClientTest.java @@ -23,9 +23,8 @@ import io.grpc.xds.XdsClient.RefCountedXdsClientObjectPool; import io.grpc.xds.XdsClient.XdsClientFactory; -import org.junit.Rule; +import org.junit.Assert; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -34,8 +33,6 @@ */ @RunWith(JUnit4.class) public class XdsClientTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); @Test public void refCountedXdsClientObjectPool_getObjectShouldMatchReturnObject() { @@ -61,9 +58,12 @@ XdsClient createXdsClient() { verify(xdsClient).shutdown(); assertThat(xdsClientPool.xdsClient).isNull(); - thrown.expect(IllegalStateException.class); - // returnOject for the 3rd time - xdsClientPool.returnObject(xdsClient); + // returnObject for the 3rd time + try { + xdsClientPool.returnObject(xdsClient); + Assert.fail(); + } catch (IllegalStateException expected) { + } } @Test @@ -79,8 +79,11 @@ XdsClient createXdsClient() { xdsClientPool.getObject(); - thrown.expect(IllegalStateException.class); - xdsClientPool.returnObject(mock(XdsClient.class)); + try { + xdsClientPool.returnObject(mock(XdsClient.class)); + Assert.fail(); + } catch (IllegalStateException expected) { + } } @Test