Replace usages of deprecated ExpectedException in grpc-api and grpc-core (#11962)

This commit is contained in:
Alex Panchenko 2025-03-21 09:30:24 +02:00 committed by GitHub
parent d2d72cda83
commit d60e6fc251
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 185 additions and 303 deletions

View File

@ -47,6 +47,7 @@ dependencies {
testImplementation project(':grpc-core') testImplementation project(':grpc-core')
testImplementation project(':grpc-testing') testImplementation project(':grpc-testing')
testImplementation libraries.guava.testlib testImplementation libraries.guava.testlib
testImplementation libraries.truth
signature (libraries.signature.java) { signature (libraries.signature.java) {
artifact { artifact {

View File

@ -16,6 +16,7 @@
package io.grpc; package io.grpc;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
@ -24,6 +25,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -37,9 +39,7 @@ import java.io.InputStream;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -49,9 +49,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class MetadataTest { public class MetadataTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
private static final Metadata.BinaryMarshaller<Fish> FISH_MARSHALLER = private static final Metadata.BinaryMarshaller<Fish> FISH_MARSHALLER =
new Metadata.BinaryMarshaller<Fish>() { new Metadata.BinaryMarshaller<Fish>() {
@Override @Override
@ -65,7 +62,7 @@ public class MetadataTest {
} }
}; };
private static class FishStreamMarsaller implements Metadata.BinaryStreamMarshaller<Fish> { private static class FishStreamMarshaller implements Metadata.BinaryStreamMarshaller<Fish> {
@Override @Override
public InputStream toStream(Fish fish) { public InputStream toStream(Fish fish) {
return new ByteArrayInputStream(FISH_MARSHALLER.toBytes(fish)); return new ByteArrayInputStream(FISH_MARSHALLER.toBytes(fish));
@ -82,7 +79,7 @@ public class MetadataTest {
} }
private static final Metadata.BinaryStreamMarshaller<Fish> FISH_STREAM_MARSHALLER = private static final Metadata.BinaryStreamMarshaller<Fish> FISH_STREAM_MARSHALLER =
new FishStreamMarsaller(); new FishStreamMarshaller();
/** A pattern commonly used to avoid unnecessary serialization of immutable objects. */ /** A pattern commonly used to avoid unnecessary serialization of immutable objects. */
private static final class FakeFishStream extends InputStream { private static final class FakeFishStream extends InputStream {
@ -121,10 +118,9 @@ public class MetadataTest {
@Test @Test
public void noPseudoHeaders() { public void noPseudoHeaders() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Invalid character"); () -> Metadata.Key.of(":test-bin", FISH_MARSHALLER));
assertThat(e).hasMessageThat().isEqualTo("Invalid character ':' in key name ':test-bin'");
Metadata.Key.of(":test-bin", FISH_MARSHALLER);
} }
@Test @Test
@ -186,8 +182,7 @@ public class MetadataTest {
Iterator<Fish> i = metadata.getAll(KEY).iterator(); Iterator<Fish> i = metadata.getAll(KEY).iterator();
assertEquals(lance, i.next()); assertEquals(lance, i.next());
thrown.expect(UnsupportedOperationException.class); assertThrows(UnsupportedOperationException.class, i::remove);
i.remove();
} }
@Test @Test
@ -271,17 +266,15 @@ public class MetadataTest {
@Test @Test
public void shortBinaryKeyName() { public void shortBinaryKeyName() {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> Metadata.Key.of("-bin", FISH_MARSHALLER));
Metadata.Key.of("-bin", FISH_MARSHALLER);
} }
@Test @Test
public void invalidSuffixBinaryKeyName() { public void invalidSuffixBinaryKeyName() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Binary header is named"); () -> Metadata.Key.of("nonbinary", FISH_MARSHALLER));
assertThat(e).hasMessageThat()
Metadata.Key.of("nonbinary", FISH_MARSHALLER); .isEqualTo("Binary header is named nonbinary. It must end with -bin");
} }
@Test @Test
@ -415,7 +408,7 @@ public class MetadataTest {
h.put(KEY_STREAMED, salmon); h.put(KEY_STREAMED, salmon);
// Get using a different marshaller instance. // Get using a different marshaller instance.
Fish fish = h.get(copyKey(KEY_STREAMED, new FishStreamMarsaller())); Fish fish = h.get(copyKey(KEY_STREAMED, new FishStreamMarshaller()));
assertEquals(salmon, fish); assertEquals(salmon, fish);
} }

View File

@ -26,9 +26,7 @@ import static org.junit.Assert.assertTrue;
import io.grpc.MethodDescriptor.Marshaller; import io.grpc.MethodDescriptor.Marshaller;
import io.grpc.MethodDescriptor.MethodType; import io.grpc.MethodDescriptor.MethodType;
import io.grpc.testing.TestMethodDescriptors; import io.grpc.testing.TestMethodDescriptors;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -37,10 +35,6 @@ import org.junit.runners.JUnit4;
*/ */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class MethodDescriptorTest { public class MethodDescriptorTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void createMethodDescriptor() { public void createMethodDescriptor() {
MethodDescriptor<String, String> descriptor = MethodDescriptor.<String, String>newBuilder() MethodDescriptor<String, String> descriptor = MethodDescriptor.<String, String>newBuilder()

View File

@ -19,6 +19,7 @@ package io.grpc;
import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Iterables.getOnlyElement;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalAnswers.delegatesTo; import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.ArgumentMatchers.same; import static org.mockito.ArgumentMatchers.same;
@ -40,7 +41,6 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentMatchers; import org.mockito.ArgumentMatchers;
@ -55,10 +55,6 @@ public class ServerInterceptorsTest {
@Rule @Rule
public final MockitoRule mocks = MockitoJUnit.rule(); public final MockitoRule mocks = MockitoJUnit.rule();
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Mock @Mock
private Marshaller<String> requestMarshaller; private Marshaller<String> requestMarshaller;
@ -111,21 +107,21 @@ public class ServerInterceptorsTest {
public void npeForNullServiceDefinition() { public void npeForNullServiceDefinition() {
ServerServiceDefinition serviceDef = null; ServerServiceDefinition serviceDef = null;
List<ServerInterceptor> interceptors = Arrays.asList(); List<ServerInterceptor> interceptors = Arrays.asList();
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class,
ServerInterceptors.intercept(serviceDef, interceptors); () -> ServerInterceptors.intercept(serviceDef, interceptors));
} }
@Test @Test
public void npeForNullInterceptorList() { public void npeForNullInterceptorList() {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class,
ServerInterceptors.intercept(serviceDefinition, (List<ServerInterceptor>) null); () -> ServerInterceptors.intercept(serviceDefinition, (List<ServerInterceptor>) null));
} }
@Test @Test
public void npeForNullInterceptor() { public void npeForNullInterceptor() {
List<ServerInterceptor> interceptors = Arrays.asList((ServerInterceptor) null); List<ServerInterceptor> interceptors = Arrays.asList((ServerInterceptor) null);
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class,
ServerInterceptors.intercept(serviceDefinition, interceptors); () -> ServerInterceptors.intercept(serviceDefinition, interceptors));
} }
@Test @Test

View File

@ -18,14 +18,13 @@ package io.grpc;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -52,9 +51,6 @@ public class ServerServiceDefinitionTest {
= ServerMethodDefinition.create(method1, methodHandler1); = ServerMethodDefinition.create(method1, methodHandler1);
private ServerMethodDefinition<String, Integer> methodDef2 private ServerMethodDefinition<String, Integer> methodDef2
= ServerMethodDefinition.create(method2, methodHandler2); = ServerMethodDefinition.create(method2, methodHandler2);
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test @Test
public void noMethods() { public void noMethods() {
@ -91,9 +87,7 @@ public class ServerServiceDefinitionTest {
ServiceDescriptor sd = new ServiceDescriptor(serviceName, method1); ServiceDescriptor sd = new ServiceDescriptor(serviceName, method1);
ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd) ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd)
.addMethod(method1, methodHandler1); .addMethod(method1, methodHandler1);
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, () -> ssd.addMethod(diffMethod1, methodHandler2));
ssd.addMethod(diffMethod1, methodHandler2)
.build();
} }
@Test @Test
@ -101,8 +95,7 @@ public class ServerServiceDefinitionTest {
ServiceDescriptor sd = new ServiceDescriptor(serviceName); ServiceDescriptor sd = new ServiceDescriptor(serviceName);
ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd) ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd)
.addMethod(methodDef1); .addMethod(methodDef1);
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, ssd::build);
ssd.build();
} }
@Test @Test
@ -110,16 +103,14 @@ public class ServerServiceDefinitionTest {
ServiceDescriptor sd = new ServiceDescriptor(serviceName, method1); ServiceDescriptor sd = new ServiceDescriptor(serviceName, method1);
ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd) ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd)
.addMethod(diffMethod1, methodHandler1); .addMethod(diffMethod1, methodHandler1);
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, ssd::build);
ssd.build();
} }
@Test @Test
public void buildMisaligned_missingMethod() { public void buildMisaligned_missingMethod() {
ServiceDescriptor sd = new ServiceDescriptor(serviceName, method1); ServiceDescriptor sd = new ServiceDescriptor(serviceName, method1);
ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd); ServerServiceDefinition.Builder ssd = ServerServiceDefinition.builder(sd);
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, ssd::build);
ssd.build();
} }
@Test @Test

View File

@ -16,17 +16,18 @@
package io.grpc; package io.grpc;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import com.google.common.truth.StringSubject;
import io.grpc.MethodDescriptor.MethodType; import io.grpc.MethodDescriptor.MethodType;
import io.grpc.testing.TestMethodDescriptors; import io.grpc.testing.TestMethodDescriptors;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -36,32 +37,27 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ServiceDescriptorTest { public class ServiceDescriptorTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void failsOnNullName() { public void failsOnNullName() {
thrown.expect(NullPointerException.class); List<MethodDescriptor<?, ?>> methods = Collections.emptyList();
thrown.expectMessage("name"); NullPointerException e = assertThrows(NullPointerException.class,
() -> new ServiceDescriptor(null, methods));
new ServiceDescriptor(null, Collections.<MethodDescriptor<?, ?>>emptyList()); assertThat(e).hasMessageThat().isEqualTo("name");
} }
@Test @Test
public void failsOnNullMethods() { public void failsOnNullMethods() {
thrown.expect(NullPointerException.class); NullPointerException e = assertThrows(NullPointerException.class,
thrown.expectMessage("methods"); () -> new ServiceDescriptor("name", (Collection<MethodDescriptor<?, ?>>) null));
assertThat(e).hasMessageThat().isEqualTo("methods");
new ServiceDescriptor("name", (Collection<MethodDescriptor<?, ?>>) null);
} }
@Test @Test
public void failsOnNullMethod() { public void failsOnNullMethod() {
thrown.expect(NullPointerException.class); List<MethodDescriptor<?, ?>> methods = Collections.singletonList(null);
thrown.expectMessage("method"); NullPointerException e = assertThrows(NullPointerException.class,
() -> new ServiceDescriptor("name", methods));
new ServiceDescriptor("name", Collections.<MethodDescriptor<?, ?>>singletonList(null)); assertThat(e).hasMessageThat().isEqualTo("method");
} }
@Test @Test
@ -69,15 +65,17 @@ public class ServiceDescriptorTest {
List<MethodDescriptor<?, ?>> descriptors = Collections.<MethodDescriptor<?, ?>>singletonList( List<MethodDescriptor<?, ?>> descriptors = Collections.<MethodDescriptor<?, ?>>singletonList(
MethodDescriptor.<Void, Void>newBuilder() MethodDescriptor.<Void, Void>newBuilder()
.setType(MethodType.UNARY) .setType(MethodType.UNARY)
.setFullMethodName(MethodDescriptor.generateFullMethodName("wrongservice", "method")) .setFullMethodName(MethodDescriptor.generateFullMethodName("wrongService", "method"))
.setRequestMarshaller(TestMethodDescriptors.voidMarshaller()) .setRequestMarshaller(TestMethodDescriptors.voidMarshaller())
.setResponseMarshaller(TestMethodDescriptors.voidMarshaller()) .setResponseMarshaller(TestMethodDescriptors.voidMarshaller())
.build()); .build());
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("service names"); () -> new ServiceDescriptor("fooService", descriptors));
StringSubject error = assertThat(e).hasMessageThat();
new ServiceDescriptor("name", descriptors); error.contains("service names");
error.contains("fooService");
error.contains("wrongService");
} }
@Test @Test
@ -96,10 +94,9 @@ public class ServiceDescriptorTest {
.setResponseMarshaller(TestMethodDescriptors.voidMarshaller()) .setResponseMarshaller(TestMethodDescriptors.voidMarshaller())
.build()); .build());
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("duplicate"); () -> new ServiceDescriptor("name", descriptors));
assertThat(e).hasMessageThat().isEqualTo("duplicate name name/method");
new ServiceDescriptor("name", descriptors);
} }
@Test @Test

View File

@ -23,6 +23,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.AdditionalAnswers.delegatesTo; import static org.mockito.AdditionalAnswers.delegatesTo;
@ -57,7 +58,6 @@ import java.util.concurrent.TimeUnit;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -76,8 +76,6 @@ import org.mockito.stubbing.Answer;
public class AbstractClientStreamTest { public class AbstractClientStreamTest {
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); @Rule public final MockitoRule mocks = MockitoJUnit.rule();
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
private final StatsTraceContext statsTraceCtx = StatsTraceContext.NOOP; private final StatsTraceContext statsTraceCtx = StatsTraceContext.NOOP;
private final TransportTracer transportTracer = new TransportTracer(); private final TransportTracer transportTracer = new TransportTracer();
@ -136,9 +134,7 @@ public class AbstractClientStreamTest {
AbstractClientStream stream = AbstractClientStream stream =
new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer); new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer);
stream.start(listener); stream.start(listener);
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> stream.cancel(null));
stream.cancel(null);
} }
@Test @Test
@ -164,9 +160,7 @@ public class AbstractClientStreamTest {
AbstractClientStream stream = AbstractClientStream stream =
new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer); new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer);
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> stream.start(null));
stream.start(null);
} }
@Test @Test
@ -174,9 +168,7 @@ public class AbstractClientStreamTest {
AbstractClientStream stream = AbstractClientStream stream =
new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer); new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer);
stream.start(mockListener); stream.start(mockListener);
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, () -> stream.start(mockListener));
stream.start(mockListener);
} }
@Test @Test
@ -188,8 +180,7 @@ public class AbstractClientStreamTest {
TransportState state = stream.transportState(); TransportState state = stream.transportState();
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> state.inboundDataReceived(null));
state.inboundDataReceived(null);
} }
@Test @Test
@ -212,8 +203,8 @@ public class AbstractClientStreamTest {
TransportState state = stream.transportState(); TransportState state = stream.transportState();
thrown.expect(IllegalStateException.class); Metadata headers = new Metadata();
state.inboundHeadersReceived(new Metadata()); assertThrows(IllegalStateException.class, () -> state.inboundHeadersReceived(headers));
} }
@Test @Test

View File

@ -18,6 +18,7 @@ package io.grpc.internal;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalAnswers.delegatesTo; import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -45,9 +46,7 @@ import java.util.LinkedList;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -60,9 +59,6 @@ public class AbstractServerStreamTest {
private static final int TIMEOUT_MS = 1000; private static final int TIMEOUT_MS = 1000;
private static final int MAX_MESSAGE_SIZE = 100; private static final int MAX_MESSAGE_SIZE = 100;
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
private final WritableBufferAllocator allocator = new WritableBufferAllocator() { private final WritableBufferAllocator allocator = new WritableBufferAllocator() {
@Override @Override
public WritableBuffer allocate(int capacityHint) { public WritableBuffer allocate(int capacityHint) {
@ -226,9 +222,9 @@ public class AbstractServerStreamTest {
public void setListener_setOnlyOnce() { public void setListener_setOnlyOnce() {
TransportState state = stream.transportState(); TransportState state = stream.transportState();
state.setListener(new ServerStreamListenerBase()); state.setListener(new ServerStreamListenerBase());
thrown.expect(IllegalStateException.class);
state.setListener(new ServerStreamListenerBase()); ServerStreamListenerBase listener2 = new ServerStreamListenerBase();
assertThrows(IllegalStateException.class, () -> state.setListener(listener2));
} }
@Test @Test
@ -238,8 +234,7 @@ public class AbstractServerStreamTest {
TransportState state = stream.transportState(); TransportState state = stream.transportState();
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, state::onStreamAllocated);
state.onStreamAllocated();
} }
@Test @Test
@ -255,8 +250,7 @@ public class AbstractServerStreamTest {
public void setListener_failsOnNull() { public void setListener_failsOnNull() {
TransportState state = stream.transportState(); TransportState state = stream.transportState();
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> state.setListener(null));
state.setListener(null);
} }
// TODO(ericgribkoff) This test is only valid if deframeInTransportThread=true, as otherwise the // TODO(ericgribkoff) This test is only valid if deframeInTransportThread=true, as otherwise the
@ -284,9 +278,7 @@ public class AbstractServerStreamTest {
@Test @Test
public void writeHeaders_failsOnNullHeaders() { public void writeHeaders_failsOnNullHeaders() {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> stream.writeHeaders(null, true));
stream.writeHeaders(null, true);
} }
@Test @Test
@ -336,16 +328,13 @@ public class AbstractServerStreamTest {
@Test @Test
public void close_failsOnNullStatus() { public void close_failsOnNullStatus() {
thrown.expect(NullPointerException.class); Metadata trailers = new Metadata();
assertThrows(NullPointerException.class, () -> stream.close(null, trailers));
stream.close(null, new Metadata());
} }
@Test @Test
public void close_failsOnNullMetadata() { public void close_failsOnNullMetadata() {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> stream.close(Status.INTERNAL, null));
stream.close(Status.INTERNAL, null);
} }
@Test @Test
@ -451,4 +440,3 @@ public class AbstractServerStreamTest {
} }
} }
} }

View File

@ -27,9 +27,7 @@ import com.google.common.util.concurrent.MoreExecutors;
import io.grpc.ConnectivityState; import io.grpc.ConnectivityState;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -38,10 +36,6 @@ import org.junit.runners.JUnit4;
*/ */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ConnectivityStateManagerTest { public class ConnectivityStateManagerTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final FakeClock executor = new FakeClock(); private final FakeClock executor = new FakeClock();
private final ConnectivityStateManager state = new ConnectivityStateManager(); private final ConnectivityStateManager state = new ConnectivityStateManager();
private final LinkedList<ConnectivityState> sink = new LinkedList<>(); private final LinkedList<ConnectivityState> sink = new LinkedList<>();
@ -75,7 +69,7 @@ public class ConnectivityStateManagerTest {
assertEquals(1, sink.size()); assertEquals(1, sink.size());
assertEquals(TRANSIENT_FAILURE, sink.poll()); assertEquals(TRANSIENT_FAILURE, sink.poll());
} }
@Test @Test
public void registerCallbackAfterStateChanged() { public void registerCallbackAfterStateChanged() {
state.gotoState(CONNECTING); state.gotoState(CONNECTING);

View File

@ -22,6 +22,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -35,6 +36,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import com.google.common.base.Stopwatch; import com.google.common.base.Stopwatch;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.net.InetAddresses; import com.google.common.net.InetAddresses;
@ -82,7 +84,6 @@ import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.DisableOnDebug; import org.junit.rules.DisableOnDebug;
import org.junit.rules.ExpectedException;
import org.junit.rules.TestRule; import org.junit.rules.TestRule;
import org.junit.rules.Timeout; import org.junit.rules.Timeout;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -99,8 +100,6 @@ public class DnsNameResolverTest {
@Rule public final TestRule globalTimeout = new DisableOnDebug(Timeout.seconds(10)); @Rule public final TestRule globalTimeout = new DisableOnDebug(Timeout.seconds(10));
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); @Rule public final MockitoRule mocks = MockitoJUnit.rule();
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
private final Map<String, ?> serviceConfig = new LinkedHashMap<>(); private final Map<String, ?> serviceConfig = new LinkedHashMap<>();
@ -914,9 +913,10 @@ public class DnsNameResolverTest {
public void maybeChooseServiceConfig_failsOnMisspelling() { public void maybeChooseServiceConfig_failsOnMisspelling() {
Map<String, Object> bad = new LinkedHashMap<>(); Map<String, Object> bad = new LinkedHashMap<>();
bad.put("parcentage", 1.0); bad.put("parcentage", 1.0);
thrown.expectMessage("Bad key"); Random random = new Random();
VerifyException e = assertThrows(VerifyException.class,
DnsNameResolver.maybeChooseServiceConfig(bad, new Random(), "host"); () -> DnsNameResolver.maybeChooseServiceConfig(bad, random, "host"));
assertThat(e).hasMessageThat().isEqualTo("Bad key: parcentage=1.0");
} }
@Test @Test
@ -1155,25 +1155,25 @@ public class DnsNameResolverTest {
} }
@Test @Test
public void parseTxtResults_badTypeFails() throws Exception { public void parseTxtResults_badTypeFails() {
List<String> txtRecords = new ArrayList<>(); List<String> txtRecords = new ArrayList<>();
txtRecords.add("some_record"); txtRecords.add("some_record");
txtRecords.add("grpc_config={}"); txtRecords.add("grpc_config={}");
thrown.expect(ClassCastException.class); ClassCastException e = assertThrows(ClassCastException.class,
thrown.expectMessage("wrong type"); () -> DnsNameResolver.parseTxtResults(txtRecords));
DnsNameResolver.parseTxtResults(txtRecords); assertThat(e).hasMessageThat().isEqualTo("wrong type {}");
} }
@Test @Test
public void parseTxtResults_badInnerTypeFails() throws Exception { public void parseTxtResults_badInnerTypeFails() {
List<String> txtRecords = new ArrayList<>(); List<String> txtRecords = new ArrayList<>();
txtRecords.add("some_record"); txtRecords.add("some_record");
txtRecords.add("grpc_config=[\"bogus\"]"); txtRecords.add("grpc_config=[\"bogus\"]");
thrown.expect(ClassCastException.class); ClassCastException e = assertThrows(ClassCastException.class,
thrown.expectMessage("not object"); () -> DnsNameResolver.parseTxtResults(txtRecords));
DnsNameResolver.parseTxtResults(txtRecords); assertThat(e).hasMessageThat().isEqualTo("value bogus for idx 0 in [bogus] is not object");
} }
@Test @Test

View File

@ -22,6 +22,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
@ -41,7 +42,6 @@ import io.grpc.testing.TestMethodDescriptors;
import java.util.ArrayList; import java.util.ArrayList;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -57,8 +57,6 @@ public class GrpcUtilTest {
new ClientStreamTracer() {} new ClientStreamTracer() {}
}; };
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); @Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Captor @Captor
@ -201,9 +199,7 @@ public class GrpcUtilTest {
@Test @Test
public void checkAuthority_failsOnNull() { public void checkAuthority_failsOnNull() {
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> GrpcUtil.checkAuthority(null));
GrpcUtil.checkAuthority(null);
} }
@Test @Test
@ -229,19 +225,18 @@ public class GrpcUtilTest {
@Test @Test
public void checkAuthority_failsOnInvalidAuthority() { public void checkAuthority_failsOnInvalidAuthority() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Invalid authority"); () -> GrpcUtil.checkAuthority("[ : : 1]"));
assertThat(e).hasMessageThat().isEqualTo("Invalid authority: [ : : 1]");
GrpcUtil.checkAuthority("[ : : 1]");
} }
@Test @Test
public void checkAuthority_userInfoNotAllowed() { public void checkAuthority_userInfoNotAllowed() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Userinfo"); () -> GrpcUtil.checkAuthority("foo@valid"));
assertThat(e).hasMessageThat()
GrpcUtil.checkAuthority("foo@valid"); .isEqualTo("Userinfo must not be present on authority: 'foo@valid'");
} }
@Test @Test

View File

@ -27,6 +27,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
@ -65,7 +66,6 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.Mock; import org.mockito.Mock;
@ -79,9 +79,6 @@ import org.mockito.junit.MockitoRule;
public class InternalSubchannelTest { public class InternalSubchannelTest {
@Rule @Rule
public final MockitoRule mocks = MockitoJUnit.rule(); public final MockitoRule mocks = MockitoJUnit.rule();
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
private static final String AUTHORITY = "fakeauthority"; private static final String AUTHORITY = "fakeauthority";
private static final String USER_AGENT = "mosaic"; private static final String USER_AGENT = "mosaic";
@ -544,8 +541,9 @@ public class InternalSubchannelTest {
public void updateAddresses_emptyEagList_throws() { public void updateAddresses_emptyEagList_throws() {
SocketAddress addr = new FakeSocketAddress(); SocketAddress addr = new FakeSocketAddress();
createInternalSubchannel(addr); createInternalSubchannel(addr);
thrown.expect(IllegalArgumentException.class); List<EquivalentAddressGroup> newAddressGroups = Collections.emptyList();
internalSubchannel.updateAddresses(Arrays.<EquivalentAddressGroup>asList()); assertThrows(IllegalArgumentException.class,
() -> internalSubchannel.updateAddresses(newAddressGroups));
} }
@Test @Test
@ -553,8 +551,7 @@ public class InternalSubchannelTest {
SocketAddress addr = new FakeSocketAddress(); SocketAddress addr = new FakeSocketAddress();
createInternalSubchannel(addr); createInternalSubchannel(addr);
List<EquivalentAddressGroup> eags = Arrays.asList((EquivalentAddressGroup) null); List<EquivalentAddressGroup> eags = Arrays.asList((EquivalentAddressGroup) null);
thrown.expect(NullPointerException.class); assertThrows(NullPointerException.class, () -> internalSubchannel.updateAddresses(eags));
internalSubchannel.updateAddresses(eags);
} }
@Test public void updateAddresses_intersecting_ready() { @Test public void updateAddresses_intersecting_ready() {

View File

@ -17,15 +17,14 @@
package io.grpc.internal; package io.grpc.internal;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import com.google.gson.stream.MalformedJsonException; import com.google.gson.stream.MalformedJsonException;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -35,10 +34,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class JsonParserTest { public class JsonParserTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void emptyObject() throws IOException { public void emptyObject() throws IOException {
assertEquals(new LinkedHashMap<String, Object>(), JsonParser.parse("{}")); assertEquals(new LinkedHashMap<String, Object>(), JsonParser.parse("{}"));
@ -75,45 +70,33 @@ public class JsonParserTest {
} }
@Test @Test
public void nanFails() throws IOException { public void nanFails() {
thrown.expect(MalformedJsonException.class); assertThrows(MalformedJsonException.class, () -> JsonParser.parse("NaN"));
JsonParser.parse("NaN");
} }
@Test @Test
public void objectEarlyEnd() throws IOException { public void objectEarlyEnd() {
thrown.expect(MalformedJsonException.class); assertThrows(MalformedJsonException.class, () -> JsonParser.parse("{foo:}"));
JsonParser.parse("{foo:}");
} }
@Test @Test
public void earlyEndArray() throws IOException { public void earlyEndArray() {
thrown.expect(EOFException.class); assertThrows(EOFException.class, () -> JsonParser.parse("[1, 2, "));
JsonParser.parse("[1, 2, ");
} }
@Test @Test
public void arrayMissingElement() throws IOException { public void arrayMissingElement() {
thrown.expect(MalformedJsonException.class); assertThrows(MalformedJsonException.class, () -> JsonParser.parse("[1, 2, ]"));
JsonParser.parse("[1, 2, ]");
} }
@Test @Test
public void objectMissingElement() throws IOException { public void objectMissingElement() {
thrown.expect(MalformedJsonException.class); assertThrows(MalformedJsonException.class, () -> JsonParser.parse("{1: "));
JsonParser.parse("{1: ");
} }
@Test @Test
public void objectNoName() throws IOException { public void objectNoName() {
thrown.expect(MalformedJsonException.class); assertThrows(MalformedJsonException.class, () -> JsonParser.parse("{: 1"));
JsonParser.parse("{: 1");
} }
@Test @Test
@ -125,9 +108,7 @@ public class JsonParserTest {
} }
@Test @Test
public void duplicate() throws IOException { public void duplicate() {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> JsonParser.parse("{\"hi\": 2, \"hi\": 3}"));
JsonParser.parse("{\"hi\": 2, \"hi\": 3}");
} }
} }

View File

@ -23,6 +23,7 @@ import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
@ -67,7 +68,6 @@ import java.util.regex.Pattern;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.Mock; import org.mockito.Mock;
@ -99,8 +99,6 @@ public class ManagedChannelImplBuilderTest {
}; };
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); @Rule public final MockitoRule mocks = MockitoJUnit.rule();
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
@Rule public final GrpcCleanupRule grpcCleanupRule = new GrpcCleanupRule(); @Rule public final GrpcCleanupRule grpcCleanupRule = new GrpcCleanupRule();
@Mock private ClientTransportFactory mockClientTransportFactory; @Mock private ClientTransportFactory mockClientTransportFactory;
@ -424,10 +422,9 @@ public class ManagedChannelImplBuilderTest {
@Test @Test
public void checkAuthority_invalidAuthorityFailed() { public void checkAuthority_invalidAuthorityFailed() {
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Invalid authority"); () -> builder.checkAuthority(DUMMY_AUTHORITY_INVALID));
assertThat(e).hasMessageThat().isEqualTo("Invalid authority: [ : : 1]");
builder.checkAuthority(DUMMY_AUTHORITY_INVALID);
} }
@Test @Test
@ -450,11 +447,10 @@ public class ManagedChannelImplBuilderTest {
@Test @Test
public void disableCheckAuthority_invalidAuthorityFailed() { public void disableCheckAuthority_invalidAuthorityFailed() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Invalid authority");
builder.disableCheckAuthority().enableCheckAuthority(); builder.disableCheckAuthority().enableCheckAuthority();
builder.checkAuthority(DUMMY_AUTHORITY_INVALID); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> builder.checkAuthority(DUMMY_AUTHORITY_INVALID));
assertThat(e).hasMessageThat().isEqualTo("Invalid authority: [ : : 1]");
} }
@Test @Test
@ -680,14 +676,12 @@ public class ManagedChannelImplBuilderTest {
@Test @Test
public void retryBufferSizeInvalidArg() { public void retryBufferSizeInvalidArg() {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> builder.retryBufferSize(0L));
builder.retryBufferSize(0L);
} }
@Test @Test
public void perRpcBufferLimitInvalidArg() { public void perRpcBufferLimitInvalidArg() {
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> builder.perRpcBufferLimit(0L));
builder.perRpcBufferLimit(0L);
} }
@Test @Test
@ -710,8 +704,7 @@ public class ManagedChannelImplBuilderTest {
Map<String, Object> config = new HashMap<>(); Map<String, Object> config = new HashMap<>();
config.put(null, "val"); config.put(null, "val");
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> builder.defaultServiceConfig(config));
builder.defaultServiceConfig(config);
} }
@Test @Test
@ -721,8 +714,7 @@ public class ManagedChannelImplBuilderTest {
Map<String, Object> config = new HashMap<>(); Map<String, Object> config = new HashMap<>();
config.put("key", subConfig); config.put("key", subConfig);
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> builder.defaultServiceConfig(config));
builder.defaultServiceConfig(config);
} }
@Test @Test
@ -730,8 +722,7 @@ public class ManagedChannelImplBuilderTest {
Map<String, Object> config = new HashMap<>(); Map<String, Object> config = new HashMap<>();
config.put("key", 3); config.put("key", 3);
thrown.expect(IllegalArgumentException.class); assertThrows(IllegalArgumentException.class, () -> builder.defaultServiceConfig(config));
builder.defaultServiceConfig(config);
} }
@Test @Test

View File

@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import static io.grpc.MethodDescriptor.MethodType.UNARY; import static io.grpc.MethodDescriptor.MethodType.UNARY;
import static io.grpc.Status.Code.UNAVAILABLE; import static io.grpc.Status.Code.UNAVAILABLE;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
@ -34,19 +35,13 @@ import io.grpc.internal.ManagedChannelServiceConfig.MethodInfo;
import io.grpc.testing.TestMethodDescriptors; import io.grpc.testing.TestMethodDescriptors;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ManagedChannelServiceConfigTest { public class ManagedChannelServiceConfigTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void managedChannelServiceConfig_shouldParseHealthCheckingConfig() throws Exception { public void managedChannelServiceConfig_shouldParseHealthCheckingConfig() throws Exception {
Map<String, ?> rawServiceConfig = Map<String, ?> rawServiceConfig =
@ -79,10 +74,9 @@ public class ManagedChannelServiceConfigTest {
Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name1, name2)); Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name1, name2));
Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Duplicate method"); () -> ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null));
assertThat(e).hasMessageThat().isEqualTo("Duplicate method name service/method");
ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null);
} }
@Test @Test
@ -92,10 +86,9 @@ public class ManagedChannelServiceConfigTest {
Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name1, name2)); Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name1, name2));
Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Duplicate service"); () -> ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null));
assertThat(e).hasMessageThat().isEqualTo("Duplicate service service");
ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null);
} }
@Test @Test
@ -107,10 +100,9 @@ public class ManagedChannelServiceConfigTest {
Map<String, ?> serviceConfig = Map<String, ?> serviceConfig =
ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig1, methodConfig2)); ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig1, methodConfig2));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("Duplicate service"); () -> ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null));
assertThat(e).hasMessageThat().isEqualTo("Duplicate service service");
ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null);
} }
@Test @Test
@ -119,10 +111,9 @@ public class ManagedChannelServiceConfigTest {
Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name)); Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name));
Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("missing service name for method method1"); () -> ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null));
assertThat(e).hasMessageThat().isEqualTo("missing service name for method method1");
ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null);
} }
@Test @Test
@ -131,10 +122,9 @@ public class ManagedChannelServiceConfigTest {
Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name)); Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name));
Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("missing service name for method method1"); () -> ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null));
assertThat(e).hasMessageThat().isEqualTo("missing service name for method method1");
ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null);
} }
@Test @Test
@ -143,10 +133,9 @@ public class ManagedChannelServiceConfigTest {
Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name)); Map<String, ?> methodConfig = ImmutableMap.of("name", ImmutableList.of(name));
Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig)); Map<String, ?> serviceConfig = ImmutableMap.of("methodConfig", ImmutableList.of(methodConfig));
thrown.expect(IllegalArgumentException.class); IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
thrown.expectMessage("missing service"); () -> ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null));
assertThat(e).hasMessageThat().isEqualTo("missing service name for method method");
ManagedChannelServiceConfig.fromServiceConfig(serviceConfig, true, 3, 4, null);
} }
@Test @Test

View File

@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat;
import static io.grpc.internal.GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE; import static io.grpc.internal.GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
@ -53,10 +54,8 @@ import java.util.Locale;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.experimental.runners.Enclosed; import org.junit.experimental.runners.Enclosed;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
@ -341,9 +340,6 @@ public class MessageDeframerTest {
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public static class SizeEnforcingInputStreamTests { public static class SizeEnforcingInputStreamTests {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public final ExpectedException thrown = ExpectedException.none();
private TestBaseStreamTracer tracer = new TestBaseStreamTracer(); private TestBaseStreamTracer tracer = new TestBaseStreamTracer();
private StatsTraceContext statsTraceCtx = new StatsTraceContext(new StreamTracer[]{tracer}); private StatsTraceContext statsTraceCtx = new StatsTraceContext(new StreamTracer[]{tracer});
@ -381,11 +377,12 @@ public class MessageDeframerTest {
new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx); new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx);
try { try {
thrown.expect(StatusRuntimeException.class); StatusRuntimeException e = assertThrows(StatusRuntimeException.class, () -> {
thrown.expectMessage("RESOURCE_EXHAUSTED: Decompressed gRPC message exceeds"); while (stream.read() != -1) {
}
while (stream.read() != -1) { });
} assertThat(e).hasMessageThat()
.isEqualTo("RESOURCE_EXHAUSTED: Decompressed gRPC message exceeds maximum size 2");
} finally { } finally {
stream.close(); stream.close();
} }
@ -427,10 +424,10 @@ public class MessageDeframerTest {
byte[] buf = new byte[10]; byte[] buf = new byte[10];
try { try {
thrown.expect(StatusRuntimeException.class); StatusRuntimeException e = assertThrows(StatusRuntimeException.class,
thrown.expectMessage("RESOURCE_EXHAUSTED: Decompressed gRPC message exceeds"); () -> stream.read(buf, 0, buf.length));
assertThat(e).hasMessageThat()
stream.read(buf, 0, buf.length); .isEqualTo("RESOURCE_EXHAUSTED: Decompressed gRPC message exceeds maximum size 2");
} finally { } finally {
stream.close(); stream.close();
} }
@ -470,10 +467,9 @@ public class MessageDeframerTest {
new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx); new MessageDeframer.SizeEnforcingInputStream(in, 2, statsTraceCtx);
try { try {
thrown.expect(StatusRuntimeException.class); StatusRuntimeException e = assertThrows(StatusRuntimeException.class, () -> stream.skip(4));
thrown.expectMessage("RESOURCE_EXHAUSTED: Decompressed gRPC message exceeds"); assertThat(e).hasMessageThat()
.isEqualTo("RESOURCE_EXHAUSTED: Decompressed gRPC message exceeds maximum size 2");
stream.skip(4);
} finally { } finally {
stream.close(); stream.close();
} }

View File

@ -16,12 +16,14 @@
package io.grpc.internal; package io.grpc.internal;
import static com.google.common.truth.Truth.assertThat;
import static io.grpc.internal.GrpcUtil.CONTENT_LENGTH_KEY; import static io.grpc.internal.GrpcUtil.CONTENT_LENGTH_KEY;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -54,7 +56,6 @@ import java.io.InputStreamReader;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -64,8 +65,6 @@ import org.mockito.junit.MockitoRule;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class ServerCallImplTest { public class ServerCallImplTest {
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); @Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Mock private ServerStream stream; @Mock private ServerStream stream;
@ -175,20 +174,20 @@ public class ServerCallImplTest {
@Test @Test
public void sendHeader_failsOnSecondCall() { public void sendHeader_failsOnSecondCall() {
call.sendHeaders(new Metadata()); call.sendHeaders(new Metadata());
thrown.expect(IllegalStateException.class); Metadata headers = new Metadata();
thrown.expectMessage("sendHeaders has already been called"); IllegalStateException e = assertThrows(IllegalStateException.class,
() -> call.sendHeaders(headers));
call.sendHeaders(new Metadata()); assertThat(e).hasMessageThat().isEqualTo("sendHeaders has already been called");
} }
@Test @Test
public void sendHeader_failsOnClosed() { public void sendHeader_failsOnClosed() {
call.close(Status.CANCELLED, new Metadata()); call.close(Status.CANCELLED, new Metadata());
thrown.expect(IllegalStateException.class); Metadata headers = new Metadata();
thrown.expectMessage("call is closed"); IllegalStateException e = assertThrows(IllegalStateException.class,
() -> call.sendHeaders(headers));
call.sendHeaders(new Metadata()); assertThat(e).hasMessageThat().isEqualTo("call is closed");
} }
@Test @Test
@ -204,18 +203,16 @@ public class ServerCallImplTest {
call.sendHeaders(new Metadata()); call.sendHeaders(new Metadata());
call.close(Status.CANCELLED, new Metadata()); call.close(Status.CANCELLED, new Metadata());
thrown.expect(IllegalStateException.class); IllegalStateException e = assertThrows(IllegalStateException.class,
thrown.expectMessage("call is closed"); () -> call.sendMessage(1234L));
assertThat(e).hasMessageThat().isEqualTo("call is closed");
call.sendMessage(1234L);
} }
@Test @Test
public void sendMessage_failsIfheadersUnsent() { public void sendMessage_failsIfheadersUnsent() {
thrown.expect(IllegalStateException.class); IllegalStateException e = assertThrows(IllegalStateException.class,
thrown.expectMessage("sendHeaders has not been called"); () -> call.sendMessage(1234L));
assertThat(e).hasMessageThat().isEqualTo("sendHeaders has not been called");
call.sendMessage(1234L);
} }
@Test @Test
@ -490,9 +487,10 @@ public class ServerCallImplTest {
InputStream inputStream = UNARY_METHOD.streamRequest(1234L); InputStream inputStream = UNARY_METHOD.streamRequest(1234L);
thrown.expect(RuntimeException.class); SingleMessageProducer producer = new SingleMessageProducer(inputStream);
thrown.expectMessage("unexpected exception"); RuntimeException e = assertThrows(RuntimeException.class,
streamListener.messagesAvailable(new SingleMessageProducer(inputStream)); () -> streamListener.messagesAvailable(producer));
assertThat(e).hasMessageThat().isEqualTo("unexpected exception");
} }
private static class LongMarshaller implements Marshaller<Long> { private static class LongMarshaller implements Marshaller<Long> {

View File

@ -26,6 +26,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.AdditionalAnswers.delegatesTo; import static org.mockito.AdditionalAnswers.delegatesTo;
@ -104,7 +105,6 @@ import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -140,8 +140,6 @@ public class ServerImplTest {
}; };
private static final String AUTHORITY = "some_authority"; private static final String AUTHORITY = "some_authority";
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule public final ExpectedException thrown = ExpectedException.none();
@Rule public final MockitoRule mocks = MockitoJUnit.rule(); @Rule public final MockitoRule mocks = MockitoJUnit.rule();
@BeforeClass @BeforeClass
@ -1228,7 +1226,7 @@ public class ServerImplTest {
assertFalse(context.get().isCancelled()); assertFalse(context.get().isCancelled());
assertEquals(1, timer.forwardNanos(1)); assertEquals(1, timer.forwardNanos(1));
assertTrue(callReference.get().isCancelled()); assertTrue(callReference.get().isCancelled());
assertTrue(context.get().isCancelled()); assertTrue(context.get().isCancelled());
assertThat(context.get().cancellationCause()).isNotNull(); assertThat(context.get().cancellationCause()).isNotNull();
@ -1260,9 +1258,8 @@ public class ServerImplTest {
public void getPortBeforeStartedFails() { public void getPortBeforeStartedFails() {
transportServer = new SimpleServer(); transportServer = new SimpleServer();
createServer(); createServer();
thrown.expect(IllegalStateException.class); IllegalStateException e = assertThrows(IllegalStateException.class, () -> server.getPort());
thrown.expectMessage("started"); assertThat(e).hasMessageThat().isEqualTo("Not started");
server.getPort();
} }
@Test @Test
@ -1271,9 +1268,8 @@ public class ServerImplTest {
createAndStartServer(); createAndStartServer();
server.shutdown(); server.shutdown();
server.awaitTermination(); server.awaitTermination();
thrown.expect(IllegalStateException.class); IllegalStateException e = assertThrows(IllegalStateException.class, () -> server.getPort());
thrown.expectMessage("terminated"); assertThat(e).hasMessageThat().isEqualTo("Already terminated");
server.getPort();
} }
@Test @Test

View File

@ -24,6 +24,7 @@ import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
@ -76,9 +77,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
@ -209,10 +208,6 @@ public abstract class AbstractTransportTest {
} }
})); }));
@SuppressWarnings("deprecation") // https://github.com/grpc/grpc-java/issues/7467
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before @Before
public void setUp() { public void setUp() {
server = newServer(Arrays.asList(serverStreamTracerFactory)); server = newServer(Arrays.asList(serverStreamTracerFactory));
@ -396,8 +391,7 @@ public abstract class AbstractTransportTest {
port = ((InetSocketAddress) addr).getPort(); port = ((InetSocketAddress) addr).getPort();
} }
InternalServer server2 = newServer(port, Arrays.asList(serverStreamTracerFactory)); InternalServer server2 = newServer(port, Arrays.asList(serverStreamTracerFactory));
thrown.expect(IOException.class); assertThrows(IOException.class, () -> server2.start(new MockServerListener()));
server2.start(new MockServerListener());
} }
@Test @Test