From 38ebcc3b7949f3bab8faaa96ca605e0fe597086d Mon Sep 17 00:00:00 2001 From: Blake Li Date: Fri, 17 May 2024 17:21:13 -0400 Subject: [PATCH] test: Migrate gax unit tests to Junit 5 (#2724) This PR migrate all unit tests in Gax to Junit 5. Other than standard direct replacements, some tests need to be rewritten due to the following scenarios: - `@Rule` does not exist anymore and there is no direct replacement. We mostly use it to initialize a Mockito stub, replaced with `@ExtendWith(MockitoExtension.class)`. - Some tests were relying on try-catch to assert exceptions, replaced with `assertThrows`. e.g. [OperationsClientTest](https://github.com/googleapis/sdk-platform-java/pull/2724/files#diff-4530df761eff0854357165d951e1667d3810a5448ec2aa4b853a6331516cbde0) - Parameterized tests in [AbstractRetryingExecutorTest](https://github.com/googleapis/sdk-platform-java/pull/2724/files#diff-9c5f5c1d2fcef6c4164fc0171d01e7020aa7ebb7aa49615cf3743dc89c9b3d1d) There are a few environment variable tests can be re-written with Junit 5, so we don't need to configure a [profile](https://github.com/googleapis/sdk-platform-java/blob/main/gax-java/gax/pom.xml#L115-L128) for it anymore, but they are not in the scope of this PR. fixes: #1611. --- gax-java/dependencies.properties | 5 +- gax-java/gax-grpc/BUILD.bazel | 3 +- .../api/gax/grpc/CallOptionsUtilTest.java | 23 +-- .../google/api/gax/grpc/ChannelPoolTest.java | 45 +++-- .../api/gax/grpc/GaxGrpcPropertiesTest.java | 17 +- .../gax/grpc/GrpcApiExceptionFactoryTest.java | 23 ++- .../api/gax/grpc/GrpcCallContextTest.java | 79 +++++---- .../api/gax/grpc/GrpcCallableFactoryTest.java | 27 ++- .../api/gax/grpc/GrpcClientCallsTest.java | 28 ++-- ...GrpcDirectServerStreamingCallableTest.java | 39 ++--- .../grpc/GrpcDirectStreamControllerTest.java | 13 +- .../grpc/GrpcDirectStreamingCallableTest.java | 27 ++- .../gax/grpc/GrpcHeaderInterceptorTest.java | 17 +- .../gax/grpc/GrpcLongRunningClientTest.java | 13 +- .../api/gax/grpc/GrpcLongRunningTest.java | 17 +- .../GrpcMetadataHandlerInterceptorTest.java | 19 +-- .../gax/grpc/GrpcResponseMetadataTest.java | 58 +++---- .../api/gax/grpc/GrpcStatusCodeTest.java | 9 +- .../gax/grpc/GrpcTransportDescriptorTest.java | 25 ++- .../InstantiatingGrpcChannelProviderTest.java | 78 ++++----- .../grpc/ProtoOperationTransformersTest.java | 19 +-- .../com/google/api/gax/grpc/SettingsTest.java | 21 +-- .../com/google/api/gax/grpc/TimeoutTest.java | 35 ++-- .../grpc/testing/MockServiceHelperTest.java | 30 ++-- .../longrunning/OperationsClientTest.java | 158 +++++++++--------- gax-java/gax-httpjson/BUILD.bazel | 3 +- .../httpjson/GaxHttpJsonPropertiesTest.java | 8 +- .../gax/httpjson/HttpHeadersUtilsTest.java | 14 +- .../gax/httpjson/HttpJsonCallContextTest.java | 71 ++++---- .../httpjson/HttpJsonCallableFactoryTest.java | 11 +- .../httpjson/HttpJsonClientCallImplTest.java | 15 +- .../gax/httpjson/HttpJsonClientCallsTest.java | 21 +-- .../HttpJsonClientInterceptorTest.java | 29 ++-- .../httpjson/HttpJsonDirectCallableTest.java | 50 +++--- ...JsonDirectServerStreamingCallableTest.java | 43 +++-- .../HttpJsonLongRunningClientTest.java | 24 +-- ...HttpJsonOperationSnapshotCallableTest.java | 18 +- .../HttpJsonOperationSnapshotTest.java | 16 +- .../gax/httpjson/HttpJsonStatusCodeTest.java | 10 +- .../gax/httpjson/HttpRequestRunnableTest.java | 20 +-- ...tantiatingHttpJsonChannelProviderTest.java | 15 +- .../ProtoMessageJsonStreamIteratorTest.java | 14 +- .../ProtoMessageRequestFormatterTest.java | 26 +-- .../ProtoMessageResponseParserTest.java | 22 +-- .../ProtoOperationTransformersTest.java | 20 +-- .../gax/httpjson/ProtoRestSerializerTest.java | 48 +++--- .../google/api/gax/httpjson/RetryingTest.java | 41 +++-- .../longrunning/OperationsClientTest.java | 66 ++++---- .../stub/HttpJsonOperationsStubTest.java | 8 +- gax-java/gax/BUILD.bazel | 4 +- .../api/gax/batching/AssertByPolling.java | 2 +- .../api/gax/batching/AssertByPollingTest.java | 16 +- .../api/gax/batching/BatcherImplTest.java | 151 +++++++---------- .../api/gax/batching/BatcherStatsTest.java | 15 +- .../batching/BatchingCallSettingsTest.java | 17 +- .../DynamicFlowControlSettingsTest.java | 27 ++- .../batching/FlowControlEventStatsTest.java | 19 +-- .../api/gax/batching/FlowControllerTest.java | 134 +++++++-------- .../api/gax/batching/Semaphore64Test.java | 143 ++++++---------- .../gax/batching/ThresholdBatcherTest.java | 68 ++++---- .../google/api/gax/core/DistributionTest.java | 22 +-- .../api/gax/core/GaxPropertiesTest.java | 33 ++-- .../core/GoogleCredentialsProviderTest.java | 15 +- .../gax/longrunning/OperationFuturesTest.java | 32 ++-- .../OperationTimedPollAlgorithmTest.java | 26 +-- .../com/google/api/gax/paging/PagesTest.java | 6 +- .../AbstractRetryingExecutorTest.java | 140 +++++++++------- .../gax/retrying/BasicRetryingFutureTest.java | 23 ++- .../retrying/DirectRetryingExecutorTest.java | 5 +- .../ExponentialRetryAlgorithmTest.java | 31 ++-- .../api/gax/retrying/FailingCallable.java | 2 +- .../gax/retrying/NoopRetryingContextTest.java | 17 +- .../api/gax/retrying/RetryAlgorithmTest.java | 33 ++-- .../api/gax/retrying/RetrySettingsTest.java | 8 +- .../ScheduledRetryingExecutorTest.java | 41 ++--- .../gax/rpc/ApiClientHeaderProviderTest.java | 25 ++- .../api/gax/rpc/ApiExceptionFactoryTest.java | 41 +++-- .../google/api/gax/rpc/ApiExceptionTest.java | 21 +-- .../google/api/gax/rpc/ApiExceptionsTest.java | 74 ++++---- .../gax/rpc/ApiResultRetryAlgorithmTest.java | 19 +-- .../api/gax/rpc/AttemptCallableTest.java | 20 +-- .../google/api/gax/rpc/AuthCallableTest.java | 15 +- .../google/api/gax/rpc/BatchExecutorTest.java | 17 +- .../com/google/api/gax/rpc/BatchTest.java | 19 +-- .../google/api/gax/rpc/BatchedFutureTest.java | 11 +- .../api/gax/rpc/BatchedRequestIssuerTest.java | 97 ++++++----- .../api/gax/rpc/BatcherFactoryTest.java | 21 +-- .../api/gax/rpc/BatchingCallSettingsTest.java | 17 +- .../api/gax/rpc/BatchingCallableTest.java | 23 ++- .../com/google/api/gax/rpc/BatchingTest.java | 45 ++--- .../gax/rpc/BidiStreamingCallableTest.java | 8 +- .../com/google/api/gax/rpc/CallableTest.java | 24 ++- .../api/gax/rpc/CancellationHelpers.java | 19 +-- .../google/api/gax/rpc/CancellationTest.java | 31 ++-- .../gax/rpc/CheckingAttemptCallableTest.java | 18 +- .../google/api/gax/rpc/ClientContextTest.java | 81 +++++---- .../api/gax/rpc/ClientSettingsTest.java | 41 ++--- .../api/gax/rpc/EndpointContextTest.java | 73 ++++---- .../google/api/gax/rpc/ErrorDetailsTest.java | 43 +++-- .../api/gax/rpc/FirstElementCallableTest.java | 21 +-- .../api/gax/rpc/FixedHeaderProviderTest.java | 33 ++-- .../FixedTransportChannelProviderTest.java | 9 +- .../gax/rpc/FixedWatchdogProviderTest.java | 13 +- .../InstantiatingWatchdogProviderTest.java | 18 +- .../gax/rpc/OperationCallSettingsTest.java | 13 +- .../gax/rpc/OperationCallableImplTest.java | 77 ++++----- .../api/gax/rpc/PagedCallSettingsTest.java | 13 +- .../google/api/gax/rpc/PagedCallableTest.java | 11 +- .../com/google/api/gax/rpc/PagingTest.java | 65 +++---- .../api/gax/rpc/RequestParamsBuilderTest.java | 41 +++-- .../gax/rpc/RequestUrlParamsEncoderTest.java | 16 +- .../api/gax/rpc/RetryingCallableTest.java | 6 +- .../com/google/api/gax/rpc/RetryingTest.java | 134 ++++++--------- .../google/api/gax/rpc/ServerStreamTest.java | 91 ++++------ .../ServerStreamingAttemptCallableTest.java | 31 ++-- .../rpc/ServerStreamingCallSettingsTest.java | 21 +-- .../gax/rpc/ServerStreamingCallableTest.java | 37 ++-- .../api/gax/rpc/SpoolingCallableTest.java | 23 ++- .../api/gax/rpc/StreamingCallableTest.java | 21 +-- .../gax/rpc/StreamingRetryAlgorithmTest.java | 21 +-- .../gax/rpc/TranslatingUnaryCallableTest.java | 9 +- .../api/gax/rpc/UnaryCallSettingsTest.java | 23 ++- .../google/api/gax/rpc/UnaryCallableTest.java | 21 +-- .../com/google/api/gax/rpc/WatchdogTest.java | 35 ++-- .../internal/ApiCallContextOptionsTest.java | 15 +- .../api/gax/rpc/internal/HeadersTest.java | 11 +- .../QuotaProjectIdHidingCredentialsTest.java | 31 ++-- .../AbstractMtlsTransportChannelTest.java | 29 ++-- .../api/gax/rpc/mtls/MtlsProviderTest.java | 78 +++++---- .../gax/tracing/MetricsTracerFactoryTest.java | 14 +- .../api/gax/tracing/MetricsTracerTest.java | 51 +++--- .../OpenTelemetryMetricsRecorderTest.java | 37 ++-- .../tracing/OpencensusTracerFactoryTest.java | 30 ++-- .../api/gax/tracing/OpencensusTracerTest.java | 46 +++-- .../api/gax/tracing/TraceFinisherTest.java | 21 +-- .../tracing/TracedBatchingCallableTest.java | 30 ++-- .../gax/tracing/TracedBidiCallableTest.java | 39 ++--- .../api/gax/tracing/TracedCallableTest.java | 25 +-- .../TracedClientStreamingCallableTest.java | 36 ++-- .../tracing/TracedOperationCallableTest.java | 35 ++-- .../TracedServerStreamingCallableTest.java | 35 ++-- .../gax/tracing/TracedUnaryCallableTest.java | 33 ++-- gax-java/pom.xml | 33 ++-- 143 files changed, 2143 insertions(+), 2563 deletions(-) diff --git a/gax-java/dependencies.properties b/gax-java/dependencies.properties index a41774c6a9..5173381139 100644 --- a/gax-java/dependencies.properties +++ b/gax-java/dependencies.properties @@ -79,9 +79,12 @@ maven.org_graalvm_sdk=org.graalvm.sdk:graal-sdk:22.3.5 # Testing maven artifacts maven.junit_junit=junit:junit:4.13.2 -maven.org_mockito_mockito_core=org.mockito:mockito-core:2.28.2 +maven.org_mockito_mockito_core=org.mockito:mockito-core:4.11.0 +maven.org_mockito_mockito_junit_jupiter=org.mockito:mockito-junit-jupiter:4.11.0 maven.org_hamcrest_hamcrest_core=org.hamcrest:hamcrest-core:1.3 maven.com_google_truth_truth=com.google.truth:truth:1.4.2 maven.com_googlecode_java_diff_utils_diffutils=com.googlecode.java-diff-utils:diffutils:1.3.0 maven.net_bytebuddy_byte_buddy=net.bytebuddy:byte-buddy:1.14.15 maven.org_objenesis_objenesis=org.objenesis:objenesis:2.6 +maven.org_junit_jupiter_junit_jupiter_api=org.junit.jupiter:junit-jupiter-api:5.10.2 +maven.org_junit_jupiter_junit_jupiter_params=org.junit.jupiter:junit-jupiter-params:5.10.2 diff --git a/gax-java/gax-grpc/BUILD.bazel b/gax-java/gax-grpc/BUILD.bazel index f1dfe02fc6..be224ff3f8 100644 --- a/gax-java/gax-grpc/BUILD.bazel +++ b/gax-java/gax-grpc/BUILD.bazel @@ -35,8 +35,9 @@ _COMPILE_DEPS = [ ] _TEST_COMPILE_DEPS = [ - "@junit_junit//jar", + "@org_junit_jupiter_junit_jupiter_api//jar", "@org_mockito_mockito_core//jar", + "@org_mockito_mockito_junit_jupiter//jar", "@com_google_truth_truth//jar", "@io_grpc_grpc_java//core:inprocess", "@com_google_api_grpc_grpc_google_common_protos//jar", diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/CallOptionsUtilTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/CallOptionsUtilTest.java index 26a6b925f8..e9bba5d63d 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/CallOptionsUtilTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/CallOptionsUtilTest.java @@ -29,19 +29,20 @@ */ package com.google.api.gax.grpc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.ImmutableMap; import io.grpc.CallOptions; import io.grpc.Metadata.Key; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CallOptionsUtilTest { +class CallOptionsUtilTest { @Test - public void testPutAndGetDynamicHeaderOption() { + void testPutAndGetDynamicHeaderOption() { String encodedRequestParams = "param1=value¶m2.param3=value23"; CallOptions options = CallOptionsUtil.putRequestParamsDynamicHeaderOption( @@ -54,7 +55,7 @@ public void testPutAndGetDynamicHeaderOption() { } @Test - public void testPutAndGetDynamicHeaderOptionEmpty() { + void testPutAndGetDynamicHeaderOptionEmpty() { CallOptions options = CallOptionsUtil.putRequestParamsDynamicHeaderOption(CallOptions.DEFAULT, ""); assertSame(CallOptions.DEFAULT, options); @@ -62,8 +63,10 @@ public void testPutAndGetDynamicHeaderOptionEmpty() { assertTrue(headers.isEmpty()); } - @Test(expected = NullPointerException.class) - public void testPutAndGetHeaderOptionNull() { - CallOptionsUtil.putRequestParamsDynamicHeaderOption(CallOptions.DEFAULT, null); + @Test + void testPutAndGetHeaderOptionNull() { + assertThrows( + NullPointerException.class, + () -> CallOptionsUtil.putRequestParamsDynamicHeaderOption(CallOptions.DEFAULT, null)); } } diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/ChannelPoolTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/ChannelPoolTest.java index ebc941ec0a..b9d6ae6c6d 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/ChannelPoolTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/ChannelPoolTest.java @@ -69,29 +69,26 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.mockito.stubbing.Answer; -@RunWith(JUnit4.class) -public class ChannelPoolTest { +class ChannelPoolTest { private static final int DEFAULT_AWAIT_TERMINATION_SEC = 10; private ChannelPool pool; - @After - public void cleanup() throws InterruptedException { + @AfterEach + void cleanup() throws InterruptedException { Preconditions.checkNotNull(pool, "Channel pool was never created"); pool.shutdown(); pool.awaitTermination(DEFAULT_AWAIT_TERMINATION_SEC, TimeUnit.SECONDS); } @Test - public void testAuthority() throws IOException { + void testAuthority() throws IOException { ManagedChannel sub1 = Mockito.mock(ManagedChannel.class); ManagedChannel sub2 = Mockito.mock(ManagedChannel.class); @@ -105,7 +102,7 @@ public void testAuthority() throws IOException { } @Test - public void testRoundRobin() throws IOException { + void testRoundRobin() throws IOException { ManagedChannel sub1 = Mockito.mock(ManagedChannel.class); ManagedChannel sub2 = Mockito.mock(ManagedChannel.class); @@ -144,7 +141,7 @@ private void verifyTargetChannel( } @Test - public void ensureEvenDistribution() throws InterruptedException, IOException { + void ensureEvenDistribution() throws InterruptedException, IOException { int numChannels = 10; final ManagedChannel[] channels = new ManagedChannel[numChannels]; final AtomicInteger[] counts = new AtomicInteger[numChannels]; @@ -197,7 +194,7 @@ public void ensureEvenDistribution() throws InterruptedException, IOException { // Test channelPrimer is called same number of times as poolSize if executorService is set to null @Test - public void channelPrimerShouldCallPoolConstruction() throws IOException { + void channelPrimerShouldCallPoolConstruction() throws IOException { ChannelPrimer mockChannelPrimer = Mockito.mock(ChannelPrimer.class); ManagedChannel channel1 = Mockito.mock(ManagedChannel.class); ManagedChannel channel2 = Mockito.mock(ManagedChannel.class); @@ -215,7 +212,7 @@ public void channelPrimerShouldCallPoolConstruction() throws IOException { // Test channelPrimer is called periodically, if there's an executorService @Test - public void channelPrimerIsCalledPeriodically() throws IOException { + void channelPrimerIsCalledPeriodically() throws IOException { ChannelPrimer mockChannelPrimer = Mockito.mock(ChannelPrimer.class); ManagedChannel channel1 = Mockito.mock(ManagedChannel.class); ManagedChannel channel2 = Mockito.mock(ManagedChannel.class); @@ -266,7 +263,7 @@ public void channelPrimerIsCalledPeriodically() throws IOException { // ---- // call should be allowed to complete and the channel should not be shutdown @Test - public void callShouldCompleteAfterCreation() throws IOException { + void callShouldCompleteAfterCreation() throws IOException { ManagedChannel underlyingChannel = Mockito.mock(ManagedChannel.class); ManagedChannel replacementChannel = Mockito.mock(ManagedChannel.class); FakeChannelFactory channelFactory = @@ -314,7 +311,7 @@ public void callShouldCompleteAfterCreation() throws IOException { // call should be allowed to complete and the channel should not be shutdown @Test - public void callShouldCompleteAfterStarted() throws IOException { + void callShouldCompleteAfterStarted() throws IOException { final ManagedChannel underlyingChannel = Mockito.mock(ManagedChannel.class); ManagedChannel replacementChannel = Mockito.mock(ManagedChannel.class); @@ -359,7 +356,7 @@ public void callShouldCompleteAfterStarted() throws IOException { // Channel should be shutdown after a refresh all the calls have completed @Test - public void channelShouldShutdown() throws IOException { + void channelShouldShutdown() throws IOException { ManagedChannel underlyingChannel = Mockito.mock(ManagedChannel.class); ManagedChannel replacementChannel = Mockito.mock(ManagedChannel.class); @@ -402,7 +399,7 @@ public void channelShouldShutdown() throws IOException { } @Test - public void channelRefreshShouldSwapChannels() throws IOException { + void channelRefreshShouldSwapChannels() throws IOException { ManagedChannel underlyingChannel1 = Mockito.mock(ManagedChannel.class); ManagedChannel underlyingChannel2 = Mockito.mock(ManagedChannel.class); @@ -442,7 +439,7 @@ public void channelRefreshShouldSwapChannels() throws IOException { } @Test - public void channelCountShouldNotChangeWhenOutstandingRpcsAreWithinLimits() throws Exception { + void channelCountShouldNotChangeWhenOutstandingRpcsAreWithinLimits() throws Exception { ScheduledExecutorService executor = Mockito.mock(ScheduledExecutorService.class); List channels = new ArrayList<>(); @@ -521,7 +518,7 @@ public void channelCountShouldNotChangeWhenOutstandingRpcsAreWithinLimits() thro } @Test - public void removedIdleChannelsAreShutdown() throws Exception { + void removedIdleChannelsAreShutdown() throws Exception { ScheduledExecutorService executor = Mockito.mock(ScheduledExecutorService.class); List channels = new ArrayList<>(); @@ -561,7 +558,7 @@ public void removedIdleChannelsAreShutdown() throws Exception { } @Test - public void removedActiveChannelsAreShutdown() throws Exception { + void removedActiveChannelsAreShutdown() throws Exception { ScheduledExecutorService executor = Mockito.mock(ScheduledExecutorService.class); List channels = new ArrayList<>(); @@ -622,7 +619,7 @@ public void removedActiveChannelsAreShutdown() throws Exception { } @Test - public void testReleasingClientCallCancelEarly() throws IOException { + void testReleasingClientCallCancelEarly() throws IOException { ClientCall mockClientCall = Mockito.mock(ClientCall.class); Mockito.doAnswer(invocation -> null).when(mockClientCall).cancel(Mockito.any(), Mockito.any()); ManagedChannel fakeChannel = Mockito.mock(ManagedChannel.class); @@ -650,7 +647,7 @@ public void testReleasingClientCallCancelEarly() throws IOException { Color request = Color.newBuilder().setRed(0.5f).build(); IllegalStateException e = - Assert.assertThrows( + Assertions.assertThrows( IllegalStateException.class, () -> streamingCallable.call( @@ -675,7 +672,7 @@ public void onComplete() {} } @Test - public void testDoubleRelease() throws Exception { + void testDoubleRelease() throws Exception { FakeLogHandler logHandler = new FakeLogHandler(); ChannelPool.LOG.addHandler(logHandler); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GaxGrpcPropertiesTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GaxGrpcPropertiesTest.java index 4174312272..651b17e712 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GaxGrpcPropertiesTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GaxGrpcPropertiesTest.java @@ -29,31 +29,28 @@ */ package com.google.api.gax.grpc; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.regex.Pattern; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class GaxGrpcPropertiesTest { +class GaxGrpcPropertiesTest { @Test - public void testGrpcVersion() { + void testGrpcVersion() { String grpcVersion = GaxGrpcProperties.getGrpcVersion(); assertTrue(Pattern.compile("^\\d+\\.\\d+\\.\\d+").matcher(grpcVersion).find()); } @Test - public void testGaxGrpcVersion() { + void testGaxGrpcVersion() { String gaxGrpcVersion = GaxGrpcProperties.getGaxGrpcVersion(); assertNotNull(gaxGrpcVersion); } @Test - public void testDefaultHeaderPattern() { + void testDefaultHeaderPattern() { assertTrue( GaxGrpcProperties.getDefaultApiClientHeaderPattern() .matcher("gl-java/1.8_00 gapic/1.2.3-alpha gax/1.5.0 grpc/1.7.0") diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcApiExceptionFactoryTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcApiExceptionFactoryTest.java index bb8febef54..e4e86d589d 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcApiExceptionFactoryTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcApiExceptionFactoryTest.java @@ -44,13 +44,10 @@ import io.grpc.StatusException; import io.grpc.StatusRuntimeException; import java.util.Collections; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class GrpcApiExceptionFactoryTest { +class GrpcApiExceptionFactoryTest { private static final ErrorInfo ERROR_INFO = ErrorInfo.newBuilder() @@ -72,13 +69,13 @@ public class GrpcApiExceptionFactoryTest { private GrpcApiExceptionFactory factory; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { factory = new GrpcApiExceptionFactory(Collections.emptySet()); } @Test - public void create_shouldCreateApiExceptionWithErrorDetailsForStatusException() { + void create_shouldCreateApiExceptionWithErrorDetailsForStatusException() { Metadata trailers = new Metadata(); Status status = Status.newBuilder().addAllDetails(RAW_ERROR_MESSAGES).build(); trailers.put( @@ -91,7 +88,7 @@ public void create_shouldCreateApiExceptionWithErrorDetailsForStatusException() } @Test - public void create_shouldCreateApiExceptionWithErrorDetailsForStatusRuntimeException() { + void create_shouldCreateApiExceptionWithErrorDetailsForStatusRuntimeException() { Metadata trailers = new Metadata(); Status status = Status.newBuilder().addAllDetails(RAW_ERROR_MESSAGES).build(); trailers.put( @@ -104,7 +101,7 @@ public void create_shouldCreateApiExceptionWithErrorDetailsForStatusRuntimeExcep } @Test - public void create_shouldCreateApiExceptionWithNoErrorDetailsIfMetadataIsNull() { + void create_shouldCreateApiExceptionWithNoErrorDetailsIfMetadataIsNull() { StatusRuntimeException statusException = new StatusRuntimeException(GRPC_STATUS, null); ApiException actual = factory.create(statusException); @@ -113,7 +110,7 @@ public void create_shouldCreateApiExceptionWithNoErrorDetailsIfMetadataIsNull() } @Test - public void create_shouldCreateApiExceptionWithNoErrorDetailsIfMetadataDoesNotHaveErrorDetails() { + void create_shouldCreateApiExceptionWithNoErrorDetailsIfMetadataDoesNotHaveErrorDetails() { StatusRuntimeException statusException = new StatusRuntimeException(GRPC_STATUS, new Metadata()); @@ -123,7 +120,7 @@ public void create_shouldCreateApiExceptionWithNoErrorDetailsIfMetadataDoesNotHa } @Test - public void create_shouldCreateApiExceptionWithNoErrorDetailsIfStatusIsMalformed() { + void create_shouldCreateApiExceptionWithNoErrorDetailsIfStatusIsMalformed() { Metadata trailers = new Metadata(); Status status = Status.newBuilder().addDetails(Any.pack(ERROR_INFO)).build(); byte[] bytes = status.toByteArray(); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallContextTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallContextTest.java index e67c4c13c2..02d922c635 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallContextTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallContextTest.java @@ -29,9 +29,9 @@ */ package com.google.api.gax.grpc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; @@ -53,21 +53,18 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class GrpcCallContextTest { +class GrpcCallContextTest { @Test - public void testNullToSelfWrongType() { + void testNullToSelfWrongType() { try { GrpcCallContext.createDefault().nullToSelf(FakeCallContext.createDefault()); - Assert.fail("GrpcCallContext should have thrown an exception"); + Assertions.fail("GrpcCallContext should have thrown an exception"); } catch (IllegalArgumentException expected) { Truth.assertThat(expected) .hasMessageThat() @@ -76,7 +73,7 @@ public void testNullToSelfWrongType() { } @Test - public void testWithCredentials() { + void testWithCredentials() { Credentials credentials = Mockito.mock(Credentials.class); GrpcCallContext emptyContext = GrpcCallContext.createDefault(); assertNull(emptyContext.getCallOptions().getCredentials()); @@ -85,7 +82,7 @@ public void testWithCredentials() { } @Test - public void testWithTransportChannel() { + void testWithTransportChannel() { ManagedChannel channel = Mockito.mock(ManagedChannel.class); GrpcCallContext context = GrpcCallContext.createDefault().withTransportChannel(GrpcTransportChannel.create(channel)); @@ -93,21 +90,21 @@ public void testWithTransportChannel() { } @Test - public void testWithTransportChannelWrongType() { + void testWithTransportChannelWrongType() { FakeChannel channel = new FakeChannel(); try { GrpcCallContext.createDefault().withTransportChannel(FakeTransportChannel.create(channel)); - Assert.fail("GrpcCallContext should have thrown an exception"); + Assertions.fail("GrpcCallContext should have thrown an exception"); } catch (IllegalArgumentException expected) { Truth.assertThat(expected).hasMessageThat().contains("Expected GrpcTransportChannel"); } } @Test - public void testMergeWrongType() { + void testMergeWrongType() { try { GrpcCallContext.createDefault().merge(FakeCallContext.createDefault()); - Assert.fail("GrpcCallContext should have thrown an exception"); + Assertions.fail("GrpcCallContext should have thrown an exception"); } catch (IllegalArgumentException expected) { Truth.assertThat(expected) .hasMessageThat() @@ -116,7 +113,7 @@ public void testMergeWrongType() { } @Test - public void testWithRequestParamsDynamicHeaderOption() { + void testWithRequestParamsDynamicHeaderOption() { String encodedRequestParams = "param1=value¶m2.param3=value23"; GrpcCallContext context = GrpcCallContext.createDefault().withRequestParamsDynamicHeaderOption(encodedRequestParams); @@ -129,22 +126,22 @@ public void testWithRequestParamsDynamicHeaderOption() { } @Test - public void testWithTimeout() { + void testWithTimeout() { assertNull(GrpcCallContext.createDefault().withTimeout(null).getTimeout()); } @Test - public void testWithNegativeTimeout() { + void testWithNegativeTimeout() { assertNull(GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(-1L)).getTimeout()); } @Test - public void testWithZeroTimeout() { + void testWithZeroTimeout() { assertNull(GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(0L)).getTimeout()); } @Test - public void testWithShorterTimeout() { + void testWithShorterTimeout() { GrpcCallContext ctxWithLongTimeout = GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(10)); @@ -157,7 +154,7 @@ public void testWithShorterTimeout() { } @Test - public void testWithLongerTimeout() { + void testWithLongerTimeout() { GrpcCallContext ctxWithShortTimeout = GrpcCallContext.createDefault().withTimeout(Duration.ofSeconds(5)); @@ -171,7 +168,7 @@ public void testWithLongerTimeout() { } @Test - public void testMergeWithNullTimeout() { + void testMergeWithNullTimeout() { Duration timeout = Duration.ofSeconds(10); GrpcCallContext baseContext = GrpcCallContext.createDefault().withTimeout(timeout); @@ -183,7 +180,7 @@ public void testMergeWithNullTimeout() { } @Test - public void testMergeWithTimeout() { + void testMergeWithTimeout() { Duration timeout = Duration.ofSeconds(19); GrpcCallContext ctx1 = GrpcCallContext.createDefault(); GrpcCallContext ctx2 = GrpcCallContext.createDefault().withTimeout(timeout); @@ -192,14 +189,14 @@ public void testMergeWithTimeout() { } @Test - public void testWithStreamingWaitTimeout() { + void testWithStreamingWaitTimeout() { Duration timeout = Duration.ofSeconds(15); GrpcCallContext context = GrpcCallContext.createDefault().withStreamWaitTimeout(timeout); Truth.assertThat(context.getStreamWaitTimeout()).isEqualTo(timeout); } @Test - public void testMergeWithNullStreamingWaitTimeout() { + void testMergeWithNullStreamingWaitTimeout() { Duration timeout = Duration.ofSeconds(10); GrpcCallContext baseContext = GrpcCallContext.createDefault().withStreamWaitTimeout(timeout); @@ -213,7 +210,7 @@ public void testMergeWithNullStreamingWaitTimeout() { } @Test - public void testWithZeroStreamingWaitTimeout() { + void testWithZeroStreamingWaitTimeout() { Duration timeout = Duration.ZERO; Truth.assertThat( GrpcCallContext.createDefault().withStreamWaitTimeout(timeout).getStreamWaitTimeout()) @@ -221,7 +218,7 @@ public void testWithZeroStreamingWaitTimeout() { } @Test - public void testMergeWithStreamingWaitTimeout() { + void testMergeWithStreamingWaitTimeout() { Duration timeout = Duration.ofSeconds(19); GrpcCallContext ctx1 = GrpcCallContext.createDefault(); GrpcCallContext ctx2 = GrpcCallContext.createDefault().withStreamWaitTimeout(timeout); @@ -230,14 +227,14 @@ public void testMergeWithStreamingWaitTimeout() { } @Test - public void testWithStreamingIdleTimeout() { + void testWithStreamingIdleTimeout() { Duration timeout = Duration.ofSeconds(15); GrpcCallContext context = GrpcCallContext.createDefault().withStreamIdleTimeout(timeout); Truth.assertThat(context.getStreamIdleTimeout()).isEqualTo(timeout); } @Test - public void testMergeWithNullStreamingIdleTimeout() { + void testMergeWithNullStreamingIdleTimeout() { Duration timeout = Duration.ofSeconds(10); GrpcCallContext baseContext = GrpcCallContext.createDefault().withStreamIdleTimeout(timeout); @@ -251,7 +248,7 @@ public void testMergeWithNullStreamingIdleTimeout() { } @Test - public void testWithZeroStreamingIdleTimeout() { + void testWithZeroStreamingIdleTimeout() { Duration timeout = Duration.ZERO; Truth.assertThat( GrpcCallContext.createDefault().withStreamIdleTimeout(timeout).getStreamIdleTimeout()) @@ -259,7 +256,7 @@ public void testWithZeroStreamingIdleTimeout() { } @Test - public void testMergeWithStreamingIdleTimeout() { + void testMergeWithStreamingIdleTimeout() { Duration timeout = Duration.ofSeconds(19); GrpcCallContext ctx1 = GrpcCallContext.createDefault(); GrpcCallContext ctx2 = GrpcCallContext.createDefault().withStreamIdleTimeout(timeout); @@ -268,7 +265,7 @@ public void testMergeWithStreamingIdleTimeout() { } @Test - public void testMergeWithCustomCallOptions() { + void testMergeWithCustomCallOptions() { CallOptions.Key key = CallOptions.Key.createWithDefault("somekey", "somedefault"); GrpcCallContext ctx1 = GrpcCallContext.createDefault(); GrpcCallContext ctx2 = @@ -283,7 +280,7 @@ public void testMergeWithCustomCallOptions() { } @Test - public void testWithExtraHeaders() { + void testWithExtraHeaders() { Map> extraHeaders = createTestExtraHeaders("key1", "value1", "key1", "value2"); GrpcCallContext ctx = GrpcCallContext.createDefault().withExtraHeaders(extraHeaders); @@ -298,7 +295,7 @@ public void testWithExtraHeaders() { } @Test - public void testMergeWithExtraHeaders() { + void testMergeWithExtraHeaders() { Map> extraHeaders1 = createTestExtraHeaders("key1", "value1", "key1", "value2"); GrpcCallContext ctx1 = GrpcCallContext.createDefault().withExtraHeaders(extraHeaders1); @@ -316,7 +313,7 @@ public void testMergeWithExtraHeaders() { } @Test - public void testMergeWithTracer() { + void testMergeWithTracer() { ApiTracer explicitTracer = Mockito.mock(ApiTracer.class); GrpcCallContext ctxWithExplicitTracer = GrpcCallContext.createDefault().withTracer(explicitTracer); @@ -338,7 +335,7 @@ public void testMergeWithTracer() { } @Test - public void testWithRetrySettings() { + void testWithRetrySettings() { RetrySettings retrySettings = Mockito.mock(RetrySettings.class); GrpcCallContext emptyContext = GrpcCallContext.createDefault(); assertNull(emptyContext.getRetrySettings()); @@ -347,7 +344,7 @@ public void testWithRetrySettings() { } @Test - public void testWithRetryableCodes() { + void testWithRetryableCodes() { Set codes = Collections.singleton(StatusCode.Code.UNAVAILABLE); GrpcCallContext emptyContext = GrpcCallContext.createDefault(); assertNull(emptyContext.getRetryableCodes()); @@ -356,7 +353,7 @@ public void testWithRetryableCodes() { } @Test - public void testWithOptions() { + void testWithOptions() { GrpcCallContext emptyCallContext = GrpcCallContext.createDefault(); ApiCallContext.Key contextKey1 = ApiCallContext.Key.create("testKey1"); ApiCallContext.Key contextKey2 = ApiCallContext.Key.create("testKey2"); @@ -374,7 +371,7 @@ public void testWithOptions() { } @Test - public void testMergeOptions() throws IOException { + void testMergeOptions() throws IOException { GrpcCallContext emptyCallContext = GrpcCallContext.createDefault(); ApiCallContext.Key contextKey1 = ApiCallContext.Key.create("testKey1"); ApiCallContext.Key contextKey2 = ApiCallContext.Key.create("testKey2"); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java index a274512e14..a24e777774 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java @@ -55,22 +55,19 @@ import io.grpc.MethodDescriptor.MethodType; import io.grpc.inprocess.InProcessChannelBuilder; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class GrpcCallableFactoryTest { +class GrpcCallableFactoryTest { private InProcessServer inprocessServer; private ManagedChannel channel; private ClientContext clientContext; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { String serverName = "fakeservice"; FakeServiceImpl serviceImpl = new FakeServiceImpl(); inprocessServer = new InProcessServer<>(serviceImpl, serverName); @@ -90,14 +87,14 @@ public void setUp() throws Exception { .build(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { channel.shutdown(); inprocessServer.stop(); } @Test - public void createServerStreamingCallableRetryableExceptions() { + void createServerStreamingCallableRetryableExceptions() { GrpcCallSettings grpcCallSettings = GrpcCallSettings.create(FakeServiceGrpc.METHOD_STREAMING_RECOGNIZE_ERROR); @@ -151,7 +148,7 @@ public void createServerStreamingCallableRetryableExceptions() { } @Test - public void testGetSpanName() { + void testGetSpanName() { @SuppressWarnings("unchecked") MethodDescriptor descriptor = MethodDescriptor.newBuilder() @@ -166,7 +163,7 @@ public void testGetSpanName() { } @Test - public void testGetSpanNameUnqualified() { + void testGetSpanNameUnqualified() { @SuppressWarnings("unchecked") MethodDescriptor descriptor = MethodDescriptor.newBuilder() @@ -181,7 +178,7 @@ public void testGetSpanNameUnqualified() { } @Test - public void testGetSpanNameInvalid() { + void testGetSpanNameInvalid() { List invalidNames = ImmutableList.of("BareMethod", "/MethodWithoutService"); for (String invalidName : invalidNames) { diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java index eb9277b2e1..a22b5fa747 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java @@ -30,7 +30,7 @@ package com.google.api.gax.grpc; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.verify; import com.google.api.gax.grpc.testing.FakeChannelFactory; @@ -58,13 +58,13 @@ import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.threeten.bp.Duration; -public class GrpcClientCallsTest { +class GrpcClientCallsTest { // Auth Library's GoogleAuthException is package-private. Copy basic functionality for tests private static class GoogleAuthException extends IOException implements Retryable { @@ -91,8 +91,8 @@ public int getRetryCount() { private Credentials credentials; private Channel mockChannel; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { credentials = Mockito.mock(Credentials.class); endpointContext = Mockito.mock(EndpointContext.class); mockChannel = Mockito.mock(Channel.class); @@ -104,7 +104,7 @@ public void setUp() throws IOException { } @Test - public void testAffinity() throws IOException { + void testAffinity() throws IOException { MethodDescriptor descriptor = FakeServiceGrpc.METHOD_RECOGNIZE; @SuppressWarnings("unchecked") @@ -138,7 +138,7 @@ public void testAffinity() throws IOException { } @Test - public void testExtraHeaders() throws IOException { + void testExtraHeaders() throws IOException { Metadata emptyHeaders = new Metadata(); final Map> extraHeaders = new HashMap<>(); extraHeaders.put( @@ -179,7 +179,7 @@ public void testExtraHeaders() throws IOException { } @Test - public void testTimeoutToDeadlineConversion() throws IOException { + void testTimeoutToDeadlineConversion() throws IOException { MethodDescriptor descriptor = FakeServiceGrpc.METHOD_RECOGNIZE; @SuppressWarnings("unchecked") @@ -209,7 +209,7 @@ public void testTimeoutToDeadlineConversion() throws IOException { } @Test - public void testTimeoutAfterDeadline() throws IOException { + void testTimeoutAfterDeadline() throws IOException { MethodDescriptor descriptor = FakeServiceGrpc.METHOD_RECOGNIZE; @SuppressWarnings("unchecked") @@ -242,7 +242,7 @@ public void testTimeoutAfterDeadline() throws IOException { } @Test - public void testTimeoutBeforeDeadline() throws IOException { + void testTimeoutBeforeDeadline() throws IOException { MethodDescriptor descriptor = FakeServiceGrpc.METHOD_RECOGNIZE; @SuppressWarnings("unchecked") @@ -279,7 +279,7 @@ public void testTimeoutBeforeDeadline() throws IOException { } @Test - public void testValidUniverseDomain() throws IOException { + void testValidUniverseDomain() throws IOException { GrpcCallContext context = GrpcCallContext.createDefault() .withChannel(mockChannel) @@ -295,7 +295,7 @@ public void testValidUniverseDomain() throws IOException { // This test is when the universe domain does not match @Test - public void testInvalidUniverseDomain() throws IOException { + void testInvalidUniverseDomain() throws IOException { Mockito.doThrow( new UnauthenticatedException( null, GrpcStatusCode.of(Status.Code.UNAUTHENTICATED), false)) @@ -319,7 +319,7 @@ public void testInvalidUniverseDomain() throws IOException { // This test is when the MDS is unable to return a valid universe domain @Test - public void testUniverseDomainNotReady_shouldRetry() throws IOException { + void testUniverseDomainNotReady_shouldRetry() throws IOException { Mockito.doThrow(new GoogleAuthException(true)) .when(endpointContext) .validateUniverseDomain(Mockito.any(Credentials.class), Mockito.any(GrpcStatusCode.class)); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectServerStreamingCallableTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectServerStreamingCallableTest.java index 5935d1d786..843ae84331 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectServerStreamingCallableTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectServerStreamingCallableTest.java @@ -59,16 +59,13 @@ import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -@RunWith(JUnit4.class) -public class GrpcDirectServerStreamingCallableTest { +class GrpcDirectServerStreamingCallableTest { private static final Color DEFAULT_REQUEST = Color.newBuilder().setRed(0.5f).build(); private static final Color ASYNC_REQUEST = DEFAULT_REQUEST.toBuilder().setGreen(1000).build(); private static final Color ERROR_REQUEST = Color.newBuilder().setRed(-1).build(); @@ -81,8 +78,8 @@ public class GrpcDirectServerStreamingCallableTest { private ServerStreamingCallSettings streamingCallSettings; private ServerStreamingCallable streamingCallable; - @Before - public void setUp() throws InstantiationException, IllegalAccessException, IOException { + @BeforeEach + void setUp() throws InstantiationException, IllegalAccessException, IOException { String serverName = "fakeservice"; FakeServiceImpl serviceImpl = new FakeServiceImpl(); inprocessServer = new InProcessServer<>(serviceImpl, serverName); @@ -109,14 +106,14 @@ public void setUp() throws InstantiationException, IllegalAccessException, IOExc clientContext); } - @After - public void tearDown() { + @AfterEach + void tearDown() { channel.shutdown(); inprocessServer.stop(); } @Test - public void testBadContext() { + void testBadContext() { streamingCallable = GrpcCallableFactory.createServerStreamingCallable( GrpcCallSettings.create(METHOD_SERVER_STREAMING_RECOGNIZE), @@ -130,7 +127,7 @@ public void testBadContext() { MoneyObserver observer = new MoneyObserver(true, latch); try { streamingCallable.call(DEFAULT_REQUEST, observer); - Assert.fail("Callable should have thrown an exception"); + Assertions.fail("Callable should have thrown an exception"); } catch (IllegalArgumentException expected) { Truth.assertThat(expected) .hasMessageThat() @@ -139,7 +136,7 @@ public void testBadContext() { } @Test - public void testServerStreamingStart() { + void testServerStreamingStart() { CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(true, latch); @@ -149,7 +146,7 @@ public void testServerStreamingStart() { } @Test - public void testServerStreaming() throws Exception { + void testServerStreaming() throws Exception { CountDownLatch latch = new CountDownLatch(2); MoneyObserver moneyObserver = new MoneyObserver(true, latch); @@ -161,7 +158,7 @@ public void testServerStreaming() throws Exception { } @Test - public void testManualFlowControl() throws Exception { + void testManualFlowControl() throws Exception { CountDownLatch latch = new CountDownLatch(2); MoneyObserver moneyObserver = new MoneyObserver(false, latch); @@ -180,7 +177,7 @@ public void testManualFlowControl() throws Exception { } @Test - public void testCancelClientCall() throws Exception { + void testCancelClientCall() throws Exception { CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(false, latch); @@ -195,7 +192,7 @@ public void testCancelClientCall() throws Exception { } @Test - public void testOnResponseError() throws Throwable { + void testOnResponseError() throws Throwable { CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(true, latch); @@ -211,7 +208,7 @@ public void testOnResponseError() throws Throwable { } @Test - public void testObserverErrorCancelsCall() throws Throwable { + void testObserverErrorCancelsCall() throws Throwable { final RuntimeException expectedCause = new RuntimeException("some error"); final SettableApiFuture actualErrorF = SettableApiFuture.create(); @@ -250,7 +247,7 @@ protected void onCompleteImpl() { } @Test - public void testBlockingServerStreaming() { + void testBlockingServerStreaming() { Color request = Color.newBuilder().setRed(0.5f).build(); ServerStream response = streamingCallable.call(request); List responseData = Lists.newArrayList(response); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamControllerTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamControllerTest.java index 96d7cf1063..64d908de28 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamControllerTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamControllerTest.java @@ -54,17 +54,16 @@ import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class GrpcDirectStreamControllerTest { +class GrpcDirectStreamControllerTest { private static final int DEFAULT_AWAIT_TERMINATION_SEC = 10; - @Test(timeout = 180_000) // ms - public void testRetryNoRaceCondition() throws Exception { + @Test + @Timeout(180) + void testRetryNoRaceCondition() throws Exception { Server server = ServerBuilder.forPort(1234).addService(new FakeService()).build().start(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 1234).usePlaintext().build(); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamingCallableTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamingCallableTest.java index 0d39f8704d..ec040efdf7 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamingCallableTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamingCallableTest.java @@ -55,22 +55,19 @@ import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -@RunWith(JUnit4.class) -public class GrpcDirectStreamingCallableTest { +class GrpcDirectStreamingCallableTest { private InProcessServer inprocessServer; private ManagedChannel channel; private FakeServiceImpl serviceImpl; private ClientContext clientContext; - @Before - public void setUp() throws InstantiationException, IllegalAccessException, IOException { + @BeforeEach + void setUp() throws InstantiationException, IllegalAccessException, IOException { String serverName = "fakeservice"; serviceImpl = new FakeServiceImpl(); inprocessServer = new InProcessServer<>(serviceImpl, serverName); @@ -89,14 +86,14 @@ public void setUp() throws InstantiationException, IllegalAccessException, IOExc .build(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { channel.shutdown(); inprocessServer.stop(); } @Test - public void testBidiStreaming() throws Exception { + void testBidiStreaming() throws Exception { BidiStreamingCallable streamingCallable = GrpcCallableFactory.createBidiStreamingCallable( GrpcCallSettings.create(METHOD_STREAMING_RECOGNIZE), null, clientContext); @@ -118,7 +115,7 @@ public void testBidiStreaming() throws Exception { } @Test - public void testBidiStreamingServerError() throws Exception { + void testBidiStreamingServerError() throws Exception { BidiStreamingCallable streamingCallable = GrpcCallableFactory.createBidiStreamingCallable( GrpcCallSettings.create(METHOD_STREAMING_RECOGNIZE_ERROR), null, clientContext); @@ -141,7 +138,7 @@ public void testBidiStreamingServerError() throws Exception { } @Test - public void testBidiStreamingClientError() throws Exception { + void testBidiStreamingClientError() throws Exception { BidiStreamingCallable streamingCallable = GrpcCallableFactory.createBidiStreamingCallable( GrpcCallSettings.create(METHOD_STREAMING_RECOGNIZE_ERROR), null, clientContext); @@ -168,7 +165,7 @@ public void testBidiStreamingClientError() throws Exception { } @Test - public void testClientStreaming() throws Exception { + void testClientStreaming() throws Exception { ClientStreamingCallable streamingCallable = GrpcCallableFactory.createClientStreamingCallable( GrpcCallSettings.create(METHOD_CLIENT_STREAMING_RECOGNIZE), null, clientContext); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcHeaderInterceptorTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcHeaderInterceptorTest.java index cf49ddbcb6..0f2fcab003 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcHeaderInterceptorTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcHeaderInterceptorTest.java @@ -29,7 +29,7 @@ */ package com.google.api.gax.grpc; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; @@ -45,18 +45,15 @@ import io.grpc.Metadata; import io.grpc.MethodDescriptor; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; /** Tests for {@link GrpcHeaderInterceptor}. */ -@RunWith(JUnit4.class) -public class GrpcHeaderInterceptorTest { +class GrpcHeaderInterceptorTest { @Mock private Channel channel; @@ -65,15 +62,15 @@ public class GrpcHeaderInterceptorTest { private static final MethodDescriptor method = FakeMethodDescriptor.create(); /** Sets up mocks. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { MockitoAnnotations.initMocks(this); when(channel.newCall(Mockito.>any(), any(CallOptions.class))) .thenReturn(call); } @Test - public void testInterceptor() { + void testInterceptor() { Map data = ImmutableMap.of("x-goog-api-client", "abcd", "user-agent", "defg"); GrpcHeaderInterceptor interceptor = new GrpcHeaderInterceptor(data); Channel intercepted = ClientInterceptors.intercept(channel, interceptor); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningClientTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningClientTest.java index dc38795054..27af7de75c 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningClientTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningClientTest.java @@ -44,15 +44,12 @@ import com.google.longrunning.Operation; import com.google.longrunning.stub.OperationsStub; import com.google.protobuf.Empty; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class GrpcLongRunningClientTest { +class GrpcLongRunningClientTest { @Test - public void get() { + void get() { OperationsStub operationsStub = mock(OperationsStub.class); when(operationsStub.getOperationCallable()) .thenReturn( @@ -75,7 +72,7 @@ public ApiFuture futureCall( } @Test - public void cancel() { + void cancel() { OperationsStub operationsStub = mock(OperationsStub.class); when(operationsStub.cancelOperationCallable()) .thenReturn( @@ -96,7 +93,7 @@ public ApiFuture futureCall( } @Test - public void delete() { + void delete() { OperationsStub operationsStub = mock(OperationsStub.class); when(operationsStub.deleteOperationCallable()) .thenReturn( diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningTest.java index 20bceeae2c..ad45b53a21 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcLongRunningTest.java @@ -66,15 +66,12 @@ import io.grpc.Status.Code; import java.io.IOException; import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class GrpcLongRunningTest { +class GrpcLongRunningTest { private static final RetrySettings FAST_RETRY_SETTINGS = RetrySettings.newBuilder() @@ -98,8 +95,8 @@ public class GrpcLongRunningTest { private FakeApiClock clock; private OperationTimedPollAlgorithm pollingAlgorithm; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { channel = mock(ManagedChannel.class); TransportChannelProvider operationsChannelProvider = mock(TransportChannelProvider.class); TransportChannel transportChannel = @@ -154,7 +151,7 @@ public void setUp() throws IOException { } @Test - public void testCall() throws IOException { + void testCall() throws IOException { Color resp = getColor(1.0f); Money meta = getMoney("UAH"); Operation resultOperation = getOperation("testCall", resp, meta, true); @@ -176,7 +173,7 @@ public void testCall() throws IOException { } @Test - public void testFutureCallPollDoneOnFirst() throws Exception { + void testFutureCallPollDoneOnFirst() throws Exception { String opName = "testFutureCallPollDoneOnFirst"; Color resp = getColor(0.5f); Money meta = getMoney("UAH"); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcMetadataHandlerInterceptorTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcMetadataHandlerInterceptorTest.java index f8306fddfa..bfcfaad960 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcMetadataHandlerInterceptorTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcMetadataHandlerInterceptorTest.java @@ -29,8 +29,8 @@ */ package com.google.api.gax.grpc; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -44,18 +44,15 @@ import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; /** Tests for {@link GrpcHeaderInterceptor}. */ -@RunWith(JUnit4.class) -public class GrpcMetadataHandlerInterceptorTest { +class GrpcMetadataHandlerInterceptorTest { private static class MutableBoolean { private volatile boolean value = false; @@ -67,15 +64,15 @@ private static class MutableBoolean { private static final MethodDescriptor method = FakeMethodDescriptor.create(); /** Sets up mocks. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { MockitoAnnotations.initMocks(this); when(channel.newCall(Mockito.>any(), any(CallOptions.class))) .thenReturn(call); } @Test - public void testInterceptor() { + void testInterceptor() { final MutableBoolean metadataHandlerCalled = new MutableBoolean(); final MutableBoolean trailingMetadataHandlerCalled = new MutableBoolean(); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcResponseMetadataTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcResponseMetadataTest.java index fba3f3f61e..bc294ef50e 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcResponseMetadataTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcResponseMetadataTest.java @@ -51,18 +51,14 @@ import io.grpc.Status; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.stub.StreamObserver; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -@RunWith(JUnit4.class) -public class GrpcResponseMetadataTest { +class GrpcResponseMetadataTest { private static final String HEADER_KEY = "inprocessheaderkey"; private static final String HEADER_VALUE = "inprocessheadervalue"; @@ -75,25 +71,23 @@ public class GrpcResponseMetadataTest { private Metadata requestHeaders = null; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { String serverName = "fakeservice"; FakeServiceImplBase serviceImpl = Mockito.mock(FakeServiceImplBase.class); Mockito.doAnswer( - new Answer() { - @Override - public Void answer(InvocationOnMock invocation) { - Color color = invocation.getArgument(0); - StreamObserver observer = invocation.getArgument(1); - observer.onNext( - Money.newBuilder() - .setCurrencyCode("USD") - .setUnits((long) (color.getRed() * 255)) - .build()); - observer.onCompleted(); - return null; - } - }) + (Answer) + invocation -> { + Color color = invocation.getArgument(0); + StreamObserver observer = invocation.getArgument(1); + observer.onNext( + Money.newBuilder() + .setCurrencyCode("USD") + .setUnits((long) (color.getRed() * 255)) + .build()); + observer.onCompleted(); + return null; + }) .when(serviceImpl) .recognize(Mockito.any(), Mockito.>any()); requestHeaders = null; @@ -150,14 +144,14 @@ public void close(Status status, Metadata trailers) { .build(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { channel.shutdown(); inprocessServer.stop(); } @Test - public void testResponseMetadataUnaryCall() { + void testResponseMetadataUnaryCall() { GrpcCallSettings grpcCallSettings = GrpcCallSettings.create(FakeServiceGrpc.METHOD_RECOGNIZE); @@ -167,19 +161,19 @@ public void testResponseMetadataUnaryCall() { UnaryCallable callable = GrpcCallableFactory.createUnaryCallable(grpcCallSettings, callSettings, clientContext); - Assert.assertNull(requestHeaders); + Assertions.assertNull(requestHeaders); GrpcResponseMetadata responseMetadata = new GrpcResponseMetadata(); callable.call(Color.getDefaultInstance(), responseMetadata.createContextWithHandlers()); - Assert.assertNotNull(requestHeaders); + Assertions.assertNotNull(requestHeaders); Metadata metadata = responseMetadata.getMetadata(); Metadata trailingMetadata = responseMetadata.getTrailingMetadata(); - Assert.assertEquals( + Assertions.assertEquals( metadata.get(Key.of(HEADER_KEY, Metadata.ASCII_STRING_MARSHALLER)), HEADER_VALUE); - Assert.assertEquals( + Assertions.assertEquals( trailingMetadata.get(Key.of(TRAILER_KEY, Metadata.ASCII_STRING_MARSHALLER)), TRAILER_VALUE); } } diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcStatusCodeTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcStatusCodeTest.java index f078a4a927..d93b9730c4 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcStatusCodeTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcStatusCodeTest.java @@ -32,14 +32,11 @@ import com.google.api.gax.rpc.StatusCode; import com.google.common.truth.Truth; import io.grpc.Status; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class GrpcStatusCodeTest { +class GrpcStatusCodeTest { @Test - public void testGrpcCodeToStatusCode() { + void testGrpcCodeToStatusCode() { testCodes(StatusCode.Code.OK, Status.Code.OK); testCodes(StatusCode.Code.CANCELLED, Status.Code.CANCELLED); testCodes(StatusCode.Code.UNKNOWN, Status.Code.UNKNOWN); diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcTransportDescriptorTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcTransportDescriptorTest.java index 456d4e73b9..51a2cd0eaf 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcTransportDescriptorTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcTransportDescriptorTest.java @@ -29,7 +29,7 @@ */ package com.google.api.gax.grpc; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; @@ -48,17 +48,14 @@ import io.grpc.StatusException; import io.grpc.StatusRuntimeException; import java.util.Collections; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class GrpcTransportDescriptorTest { +class GrpcTransportDescriptorTest { private static boolean NOT_RETRYABLE = false; private static boolean IS_RETRYABLE = true; @Test - public void translateException_StatusException_noRetry() { + void translateException_StatusException_noRetry() { Throwable originalException = new StatusException(Status.INVALID_ARGUMENT); GrpcExceptionCallable exceptionCallable = new GrpcExceptionCallable<>( @@ -73,7 +70,7 @@ public void translateException_StatusException_noRetry() { } @Test - public void translateException_StatusException_withRetry() { + void translateException_StatusException_withRetry() { Throwable originalException = new StatusException(Status.UNAVAILABLE); GrpcExceptionCallable exceptionCallable = new GrpcExceptionCallable<>( @@ -88,7 +85,7 @@ public void translateException_StatusException_withRetry() { } @Test - public void translateException_StatusRuntimeException_noRetry() { + void translateException_StatusRuntimeException_noRetry() { Throwable originalException = new StatusRuntimeException(Status.INVALID_ARGUMENT); GrpcExceptionCallable exceptionCallable = new GrpcExceptionCallable<>( @@ -103,7 +100,7 @@ public void translateException_StatusRuntimeException_noRetry() { } @Test - public void translateException_StatusRuntimeException_withRetry() { + void translateException_StatusRuntimeException_withRetry() { Throwable originalException = new StatusRuntimeException(Status.UNAVAILABLE); GrpcExceptionCallable exceptionCallable = new GrpcExceptionCallable<>( @@ -118,7 +115,7 @@ public void translateException_StatusRuntimeException_withRetry() { } @Test - public void translateException_cancelled() { + void translateException_cancelled() { GrpcExceptionCallable exceptionCallable = new GrpcExceptionCallable<>(inactiveCallable(), Collections.emptySet()); ApiFuture result = exceptionCallable.futureCall(0); @@ -129,7 +126,7 @@ public void translateException_cancelled() { } @Test - public void translateException_ApiException() { + void translateException_ApiException() { Throwable originalException = new RuntimeException("stuff went wrong"); Throwable apiException = new DataLossException( @@ -147,7 +144,7 @@ public void translateException_ApiException() { } @Test - public void translateException_RuntimeException() { + void translateException_RuntimeException() { Throwable originalException = new RuntimeException("stuff went wrong"); GrpcExceptionCallable exceptionCallable = new GrpcExceptionCallable<>( @@ -179,7 +176,7 @@ public ApiFuture futureCall(Integer request, ApiCallContext context) { }; } - public void assertInnerExceptionIsInstanceOf( + void assertInnerExceptionIsInstanceOf( Throwable thrownException, Class clazz, boolean retryable, Throwable originalException) { Truth.assertThat(thrownException).isInstanceOf(clazz); ApiException apiException = (ApiException) thrownException; diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java index a58d10ffc6..2647ac6d13 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java @@ -31,7 +31,8 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.core.ApiFunction; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder; @@ -60,18 +61,15 @@ import java.util.logging.LogRecord; import java.util.stream.Collectors; import javax.annotation.Nullable; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class InstantiatingGrpcChannelProviderTest extends AbstractMtlsTransportChannelTest { +class InstantiatingGrpcChannelProviderTest extends AbstractMtlsTransportChannelTest { @Test - public void testEndpoint() { + void testEndpoint() { String endpoint = "localhost:8080"; InstantiatingGrpcChannelProvider.Builder builder = InstantiatingGrpcChannelProvider.newBuilder(); @@ -82,18 +80,22 @@ public void testEndpoint() { assertEquals(provider.getEndpoint(), endpoint); } - @Test(expected = IllegalArgumentException.class) - public void testEndpointNoPort() { - InstantiatingGrpcChannelProvider.newBuilder().setEndpoint("localhost"); + @Test + void testEndpointNoPort() { + assertThrows( + IllegalArgumentException.class, + () -> InstantiatingGrpcChannelProvider.newBuilder().setEndpoint("localhost")); } - @Test(expected = IllegalArgumentException.class) - public void testEndpointBadPort() { - InstantiatingGrpcChannelProvider.newBuilder().setEndpoint("localhost:abcd"); + @Test + void testEndpointBadPort() { + assertThrows( + IllegalArgumentException.class, + () -> InstantiatingGrpcChannelProvider.newBuilder().setEndpoint("localhost:abcd")); } @Test - public void testKeepAlive() { + void testKeepAlive() { Duration keepaliveTime = Duration.ofSeconds(1); Duration keepaliveTimeout = Duration.ofSeconds(2); boolean keepaliveWithoutCalls = true; @@ -111,14 +113,14 @@ public void testKeepAlive() { } @Test - public void testMaxInboundMetadataSize() { + void testMaxInboundMetadataSize() { InstantiatingGrpcChannelProvider provider = InstantiatingGrpcChannelProvider.newBuilder().setMaxInboundMetadataSize(4096).build(); assertThat(provider.getMaxInboundMetadataSize()).isEqualTo(4096); } @Test - public void testCpuPoolSize() { + void testCpuPoolSize() { // happy path Builder builder = InstantiatingGrpcChannelProvider.newBuilder().setProcessorCount(2); builder.setChannelsPerCpu(2.5); @@ -135,7 +137,7 @@ public void testCpuPoolSize() { } @Test - public void testWithPoolSize() throws IOException { + void testWithPoolSize() throws IOException { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); executor.shutdown(); @@ -155,7 +157,7 @@ public void testWithPoolSize() throws IOException { } @Test - public void testToBuilder() { + void testToBuilder() { Duration keepaliveTime = Duration.ofSeconds(1); Duration keepaliveTimeout = Duration.ofSeconds(2); ApiFunction channelConfigurator = @@ -191,12 +193,12 @@ public void testToBuilder() { } @Test - public void testWithInterceptors() throws Exception { + void testWithInterceptors() throws Exception { testWithInterceptors(1); } @Test - public void testWithInterceptorsAndMultipleChannels() throws Exception { + void testWithInterceptorsAndMultipleChannels() throws Exception { testWithInterceptors(5); } @@ -218,7 +220,7 @@ private void testWithInterceptors(int numChannels) throws Exception { } @Test - public void testChannelConfigurator() throws IOException { + void testChannelConfigurator() throws IOException { final int numChannels = 5; // Create a mock configurator that will insert mock channels @@ -253,7 +255,7 @@ public void testChannelConfigurator() throws IOException { } @Test - public void testWithGCECredentials() throws IOException { + void testWithGCECredentials() throws IOException { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); executor.shutdown(); @@ -277,7 +279,7 @@ public void testWithGCECredentials() throws IOException { } @Test - public void testDirectPathXdsDisableByDefault() throws IOException { + void testDirectPathXdsDisableByDefault() throws IOException { InstantiatingGrpcChannelProvider provider = InstantiatingGrpcChannelProvider.newBuilder().setAttemptDirectPath(true).build(); @@ -285,7 +287,7 @@ public void testDirectPathXdsDisableByDefault() throws IOException { } @Test - public void testDirectPathDisallowNullCredentials() throws IOException { + void testDirectPathDisallowNullCredentials() throws IOException { InstantiatingGrpcChannelProvider provider = InstantiatingGrpcChannelProvider.newBuilder().build(); @@ -293,7 +295,7 @@ public void testDirectPathDisallowNullCredentials() throws IOException { } @Test - public void testDirectPathWithGDUEndpoint() { + void testDirectPathWithGDUEndpoint() { InstantiatingGrpcChannelProvider provider = InstantiatingGrpcChannelProvider.newBuilder() .setAttemptDirectPath(true) @@ -304,7 +306,7 @@ public void testDirectPathWithGDUEndpoint() { } @Test - public void testDirectPathWithNonGDUEndpoint() { + void testDirectPathWithNonGDUEndpoint() { InstantiatingGrpcChannelProvider provider = InstantiatingGrpcChannelProvider.newBuilder() .setAttemptDirectPath(true) @@ -315,7 +317,7 @@ public void testDirectPathWithNonGDUEndpoint() { } @Test - public void testDirectPathXdsEnabled() throws IOException { + void testDirectPathXdsEnabled() throws IOException { InstantiatingGrpcChannelProvider provider = InstantiatingGrpcChannelProvider.newBuilder() .setAttemptDirectPath(true) @@ -327,7 +329,7 @@ public void testDirectPathXdsEnabled() throws IOException { } @Test - public void testWithNonGCECredentials() throws IOException { + void testWithNonGCECredentials() throws IOException { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); executor.shutdown(); @@ -355,7 +357,7 @@ public void testWithNonGCECredentials() throws IOException { } @Test - public void testWithDirectPathDisabled() throws IOException { + void testWithDirectPathDisabled() throws IOException { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); executor.shutdown(); @@ -383,7 +385,7 @@ public void testWithDirectPathDisabled() throws IOException { } @Test - public void testWithNoDirectPathFlagSet() throws IOException { + void testWithNoDirectPathFlagSet() throws IOException { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); executor.shutdown(); @@ -410,7 +412,7 @@ public void testWithNoDirectPathFlagSet() throws IOException { } @Test - public void testWithIPv6Address() throws IOException { + void testWithIPv6Address() throws IOException { ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); executor.shutdown(); @@ -428,7 +430,7 @@ public void testWithIPv6Address() throws IOException { // Test that if ChannelPrimer is provided, it is called during creation @Test - public void testWithPrimeChannel() throws IOException { + void testWithPrimeChannel() throws IOException { // create channelProvider with different pool sizes to verify ChannelPrimer is called the // correct number of times for (int poolSize = 1; poolSize < 5; poolSize++) { @@ -452,7 +454,7 @@ public void testWithPrimeChannel() throws IOException { } @Test - public void testWithDefaultDirectPathServiceConfig() { + void testWithDefaultDirectPathServiceConfig() { InstantiatingGrpcChannelProvider provider = InstantiatingGrpcChannelProvider.newBuilder().build(); @@ -505,7 +507,7 @@ public void testWithDefaultDirectPathServiceConfig() { } @Test - public void testWithCustomDirectPathServiceConfig() { + void testWithCustomDirectPathServiceConfig() { ImmutableMap pickFirstStrategy = ImmutableMap.of("round_robin", ImmutableMap.of()); ImmutableMap childPolicy = @@ -539,7 +541,7 @@ protected Object getMtlsObjectFromTransportChannel(MtlsProvider provider) } @Test - public void testLogDirectPathMisconfigAttrempDirectPathNotSet() throws Exception { + void testLogDirectPathMisconfigAttrempDirectPathNotSet() throws Exception { FakeLogHandler logHandler = new FakeLogHandler(); InstantiatingGrpcChannelProvider.LOG.addHandler(logHandler); InstantiatingGrpcChannelProvider provider = @@ -560,7 +562,7 @@ public void testLogDirectPathMisconfigAttrempDirectPathNotSet() throws Exception } @Test - public void testLogDirectPathMisconfig_shouldNotLogInTheBuilder() { + void testLogDirectPathMisconfig_shouldNotLogInTheBuilder() { FakeLogHandler logHandler = new FakeLogHandler(); InstantiatingGrpcChannelProvider.LOG.addHandler(logHandler); InstantiatingGrpcChannelProvider.newBuilder() @@ -573,7 +575,7 @@ public void testLogDirectPathMisconfig_shouldNotLogInTheBuilder() { } @Test - public void testLogDirectPathMisconfigWrongCredential() throws Exception { + void testLogDirectPathMisconfigWrongCredential() throws Exception { FakeLogHandler logHandler = new FakeLogHandler(); InstantiatingGrpcChannelProvider.LOG.addHandler(logHandler); InstantiatingGrpcChannelProvider provider = @@ -595,7 +597,7 @@ public void testLogDirectPathMisconfigWrongCredential() throws Exception { } @Test - public void testLogDirectPathMisconfigNotOnGCE() throws Exception { + void testLogDirectPathMisconfigNotOnGCE() throws Exception { FakeLogHandler logHandler = new FakeLogHandler(); InstantiatingGrpcChannelProvider.LOG.addHandler(logHandler); InstantiatingGrpcChannelProvider provider = diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/ProtoOperationTransformersTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/ProtoOperationTransformersTest.java index 5ac43f1417..19122ff653 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/ProtoOperationTransformersTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/ProtoOperationTransformersTest.java @@ -29,7 +29,7 @@ */ package com.google.api.gax.grpc; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.gax.grpc.ProtoOperationTransformers.MetadataTransformer; import com.google.api.gax.grpc.ProtoOperationTransformers.ResponseTransformer; @@ -43,14 +43,11 @@ import com.google.type.Color; import com.google.type.Money; import io.grpc.Status.Code; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class ProtoOperationTransformersTest { +class ProtoOperationTransformersTest { @Test - public void testAnyResponseTransformer() { + void testAnyResponseTransformer() { ResponseTransformer transformer = ResponseTransformer.create(Money.class); Money inputMoney = Money.newBuilder().setCurrencyCode("USD").build(); OperationSnapshot operationSnapshot = @@ -60,7 +57,7 @@ public void testAnyResponseTransformer() { } @Test - public void testAnyResponseTransformer_exception() { + void testAnyResponseTransformer_exception() { ResponseTransformer transformer = ResponseTransformer.create(Money.class); Money inputMoney = Money.newBuilder().setCurrencyCode("USD").build(); Status status = Status.newBuilder().setCode(Code.UNAVAILABLE.value()).build(); @@ -75,7 +72,7 @@ public void testAnyResponseTransformer_exception() { } @Test - public void testAnyResponseTransformer_mismatchedTypes() { + void testAnyResponseTransformer_mismatchedTypes() { ResponseTransformer transformer = ResponseTransformer.create(Money.class); Status status = Status.newBuilder().setCode(Code.OK.value()).build(); OperationSnapshot operationSnapshot = @@ -90,7 +87,7 @@ public void testAnyResponseTransformer_mismatchedTypes() { } @Test - public void testAnyMetadataTransformer() { + void testAnyMetadataTransformer() { MetadataTransformer transformer = MetadataTransformer.create(Money.class); Money inputMoney = Money.newBuilder().setCurrencyCode("USD").build(); OperationSnapshot operationSnapshot = @@ -100,7 +97,7 @@ public void testAnyMetadataTransformer() { } @Test - public void testAnyMetadataTransformer_mismatchedTypes() { + void testAnyMetadataTransformer_mismatchedTypes() { MetadataTransformer transformer = MetadataTransformer.create(Money.class); Status status = Status.newBuilder().setCode(Code.OK.value()).build(); OperationSnapshot operationSnapshot = diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java index e24e36c686..6672f4c958 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java @@ -29,7 +29,7 @@ */ package com.google.api.gax.grpc; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.api.gax.batching.BatchingSettings; import com.google.api.gax.core.CredentialsProvider; @@ -58,14 +58,11 @@ import com.google.common.collect.Lists; import com.google.common.truth.Truth; import java.io.IOException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class SettingsTest { +class SettingsTest { interface FakePagedListResponse extends PagedListResponse {} @@ -265,7 +262,7 @@ public BatchingCallSettings.Builder fakeMethodBatching() { // ==== @Test - public void customCredentials() throws IOException { + void customCredentials() throws IOException { Credentials credentials = Mockito.mock(Credentials.class); FakeStubSettings settings = @@ -287,7 +284,7 @@ public void customCredentials() throws IOException { } @Test - public void channelCustomCredentialScopes() throws IOException { + void channelCustomCredentialScopes() throws IOException { ImmutableList inputScopes = ImmutableList.builder().add("https://www.googleapis.com/auth/fakeservice").build(); @@ -319,7 +316,7 @@ public void channelCustomCredentialScopes() throws IOException { // ==== @Test - public void callSettingsToBuilder() { + void callSettingsToBuilder() { UnaryCallSettings.Builder builderA = UnaryCallSettings.newUnaryCallSettingsBuilder(); UnaryCallSettings settingsA = builderA.build(); UnaryCallSettings.Builder builderB = settingsA.toBuilder(); @@ -329,14 +326,14 @@ public void callSettingsToBuilder() { } @Test - public void unaryCallSettingsBuilderBuildDoesNotFailUnsetProperties() { + void unaryCallSettingsBuilderBuildDoesNotFailUnsetProperties() { UnaryCallSettings.Builder builder = UnaryCallSettings.newUnaryCallSettingsBuilder(); builder.build(); } @Test - public void callSettingsBuildFromTimeoutNoRetries() { + void callSettingsBuildFromTimeoutNoRetries() { Duration timeout = Duration.ofMillis(60000); UnaryCallSettings.Builder builderA = @@ -361,6 +358,6 @@ public void callSettingsBuildFromTimeoutNoRetries() { .build()); UnaryCallSettings settingsB = builderB.build(); - assertEquals("UnaryCallSettings", settingsA, settingsB); + assertEquals(settingsA, settingsB, "UnaryCallSettings"); } } diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java index ce5f04d786..7945c23f8b 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java @@ -55,22 +55,18 @@ import io.grpc.MethodDescriptor.MethodType; import java.io.IOException; import java.util.concurrent.TimeUnit; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.mockito.quality.Strictness; +import org.mockito.junit.jupiter.MockitoExtension; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class TimeoutTest { +@ExtendWith(MockitoExtension.class) +class TimeoutTest { private static final String CALL_OPTIONS_AUTHORITY = "RETRYING_TEST"; private static final int DEADLINE_IN_DAYS = 7; private static final int DEADLINE_IN_MINUTES = 10; @@ -83,12 +79,11 @@ public class TimeoutTest { private static final Duration initialRpcTimeout = Duration.ofSeconds(DEADLINE_IN_SECONDS); private static GrpcCallContext defaultCallContext; - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @Mock private Marshaller stringMarshaller; @Mock private RequestParamsExtractor paramsExtractor; @Mock private ManagedChannel managedChannel; - @BeforeClass + @BeforeAll public static void setUp() throws IOException { EndpointContext endpointContext = Mockito.mock(EndpointContext.class); Mockito.doNothing() @@ -98,7 +93,7 @@ public static void setUp() throws IOException { } @Test - public void testNonRetryUnarySettings() { + void testNonRetryUnarySettings() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) @@ -124,7 +119,7 @@ public void testNonRetryUnarySettings() { } @Test - public void testNonRetryUnarySettingsContextWithRetry() { + void testNonRetryUnarySettingsContextWithRetry() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) @@ -164,7 +159,7 @@ public void testNonRetryUnarySettingsContextWithRetry() { } @Test - public void testNonRetryUnarySettingsWithoutInitialRpcTimeout() { + void testNonRetryUnarySettingsWithoutInitialRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) @@ -189,7 +184,7 @@ public void testNonRetryUnarySettingsWithoutInitialRpcTimeout() { } @Test - public void testNonRetryUnarySettingsWithoutIndividualRpcTimeout() { + void testNonRetryUnarySettingsWithoutIndividualRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) @@ -213,7 +208,7 @@ public void testNonRetryUnarySettingsWithoutIndividualRpcTimeout() { } @Test - public void testNonRetryServerStreamingSettings() { + void testNonRetryServerStreamingSettings() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) @@ -239,7 +234,7 @@ public void testNonRetryServerStreamingSettings() { } @Test - public void testNonRetryServerStreamingSettingsContextWithRetry() { + void testNonRetryServerStreamingSettingsContextWithRetry() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) @@ -279,7 +274,7 @@ public void testNonRetryServerStreamingSettingsContextWithRetry() { } @Test - public void testNonRetryServerStreamingSettingsWithoutInitialRpcTimeout() { + void testNonRetryServerStreamingSettingsWithoutInitialRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) @@ -304,7 +299,7 @@ public void testNonRetryServerStreamingSettingsWithoutInitialRpcTimeout() { } @Test - public void testNonRetryServerStreamingSettingsWithoutIndividualRpcTimeout() { + void testNonRetryServerStreamingSettingsWithoutIndividualRpcTimeout() { RetrySettings retrySettings = RetrySettings.newBuilder() .setTotalTimeout(totalTimeout) diff --git a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/testing/MockServiceHelperTest.java b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/testing/MockServiceHelperTest.java index 585f8ec65f..c851e93c7b 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/testing/MockServiceHelperTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/api/gax/grpc/testing/MockServiceHelperTest.java @@ -29,8 +29,9 @@ */ package com.google.api.gax.grpc.testing; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -41,15 +42,12 @@ import io.grpc.ServerServiceDefinition; import java.io.IOException; import java.util.Arrays; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; /** Tests for {@link MockServiceHelper}. */ -@RunWith(JUnit4.class) public class MockServiceHelperTest { @Mock private MockGrpcService grpcService; @Mock private MockGrpcService grpcService2; @@ -57,8 +55,8 @@ public class MockServiceHelperTest { @Mock private Server server; /** Sets up mocks. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { MockitoAnnotations.initMocks(this); when(grpcService.getServiceDefinition()) .thenReturn(ServerServiceDefinition.builder("fake-service").build()); @@ -67,28 +65,28 @@ public void setUp() { } @Test - public void testGetService() { + void testGetService() { MockServiceHelper serviceHelper = new MockServiceHelper(server, "fake-address", grpcService); Truth.assertThat(serviceHelper.getService()).isSameInstanceAs(grpcService); Truth.assertThat(serviceHelper.getServices().size()).isEqualTo(1); } - @Test(expected = IllegalStateException.class) - public void testGetServiceInvalid() { + @Test + void testGetServiceInvalid() { MockServiceHelper serviceHelper = new MockServiceHelper(server, "fake-address2", Arrays.asList(grpcService, grpcService2)); - serviceHelper.getService(); + assertThrows(IllegalStateException.class, serviceHelper::getService); } @Test - public void testStart() throws IOException { + void testStart() throws IOException { MockServiceHelper serviceHelper = new MockServiceHelper(server, "fake-address", grpcService); serviceHelper.start(); verify(server, times(1)).start(); } @Test - public void testReset() { + void testReset() { MockServiceHelper serviceHelper = new MockServiceHelper("fake-address", grpcService); serviceHelper.reset(); verify(grpcService, times(1)).getServiceDefinition(); @@ -96,7 +94,7 @@ public void testReset() { } @Test - public void testCreateChannelProvider() throws Exception { + void testCreateChannelProvider() throws Exception { MockServiceHelper serviceHelper = new MockServiceHelper("fake-address", grpcService); TransportChannel channel = serviceHelper.createChannelProvider().getTransportChannel(); assertNotNull(channel); diff --git a/gax-java/gax-grpc/src/test/java/com/google/longrunning/OperationsClientTest.java b/gax-java/gax-grpc/src/test/java/com/google/longrunning/OperationsClientTest.java index 0c5eaa302f..d438a8c4f4 100644 --- a/gax-java/gax-grpc/src/test/java/com/google/longrunning/OperationsClientTest.java +++ b/gax-java/gax-grpc/src/test/java/com/google/longrunning/OperationsClientTest.java @@ -29,6 +29,9 @@ */ package com.google.longrunning; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.gax.grpc.testing.LocalChannelProvider; import com.google.api.gax.grpc.testing.MockGrpcService; @@ -44,20 +47,19 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -public class OperationsClientTest { +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class OperationsClientTest { private static MockOperations mockOperations; private static MockServiceHelper serviceHelper; private OperationsClient client; private LocalChannelProvider channelProvider; - @BeforeClass + @BeforeAll public static void startStaticServer() { mockOperations = new MockOperations(); serviceHelper = @@ -65,13 +67,13 @@ public static void startStaticServer() { serviceHelper.start(); } - @AfterClass + @AfterAll public static void stopServer() { serviceHelper.stop(); } - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { serviceHelper.reset(); channelProvider = serviceHelper.createChannelProvider(); OperationsSettings settings = @@ -82,14 +84,14 @@ public void setUp() throws IOException { client = OperationsClient.create(settings); } - @After - public void tearDown() { + @AfterEach + void tearDown() { client.close(); } @Test @SuppressWarnings("all") - public void getOperationTest() { + void getOperationTest() { String name2 = "name2-1052831874"; boolean done = true; Operation expectedResponse = Operation.newBuilder().setName(name2).setDone(done).build(); @@ -98,34 +100,32 @@ public void getOperationTest() { String name = "name3373707"; Operation actualResponse = client.getOperation(name); - Assert.assertEquals(expectedResponse, actualResponse); + assertEquals(expectedResponse, actualResponse); List actualRequests = mockOperations.getRequests(); - Assert.assertEquals(1, actualRequests.size()); + assertEquals(1, actualRequests.size()); GetOperationRequest actualRequest = (GetOperationRequest) actualRequests.get(0); - Assert.assertEquals(name, actualRequest.getName()); + assertEquals(name, actualRequest.getName()); } @Test @SuppressWarnings("all") - public void getOperationExceptionTest() throws Exception { + void getOperationExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT); mockOperations.addException(exception); - try { - String name = "name3373707"; - - client.getOperation(name); - Assert.fail("No exception raised"); - } catch (InvalidArgumentException e) { - // Expected exception - } + String name = "name3373707"; + assertThrows( + InvalidArgumentException.class, + () -> { + client.getOperation(name); + }); } @Test @SuppressWarnings("all") - public void listOperationsTest() { + void listOperationsTest() { String nextPageToken = ""; Operation operationsElement = Operation.newBuilder().build(); List operations = Arrays.asList(operationsElement); @@ -142,37 +142,35 @@ public void listOperationsTest() { ListOperationsPagedResponse pagedListResponse = client.listOperations(name, filter); List resources = Lists.newArrayList(pagedListResponse.iterateAll()); - Assert.assertEquals(1, resources.size()); - Assert.assertEquals(expectedResponse.getOperationsList().get(0), resources.get(0)); + assertEquals(1, resources.size()); + assertEquals(expectedResponse.getOperationsList().get(0), resources.get(0)); List actualRequests = mockOperations.getRequests(); - Assert.assertEquals(1, actualRequests.size()); + assertEquals(1, actualRequests.size()); ListOperationsRequest actualRequest = (ListOperationsRequest) actualRequests.get(0); - Assert.assertEquals(name, actualRequest.getName()); - Assert.assertEquals(filter, actualRequest.getFilter()); + assertEquals(name, actualRequest.getName()); + assertEquals(filter, actualRequest.getFilter()); } @Test @SuppressWarnings("all") - public void listOperationsExceptionTest() throws Exception { + void listOperationsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT); mockOperations.addException(exception); - try { - String name = "name3373707"; - String filter = "filter-1274492040"; - - client.listOperations(name, filter); - Assert.fail("No exception raised"); - } catch (InvalidArgumentException e) { - // Expected exception - } + String name = "name3373707"; + String filter = "filter-1274492040"; + assertThrows( + InvalidArgumentException.class, + () -> { + client.listOperations(name, filter); + }); } @Test @SuppressWarnings("all") - public void cancelOperationTest() { + void cancelOperationTest() { Empty expectedResponse = Empty.newBuilder().build(); mockOperations.addResponse(expectedResponse); @@ -181,31 +179,29 @@ public void cancelOperationTest() { client.cancelOperation(name); List actualRequests = mockOperations.getRequests(); - Assert.assertEquals(1, actualRequests.size()); + assertEquals(1, actualRequests.size()); CancelOperationRequest actualRequest = (CancelOperationRequest) actualRequests.get(0); - Assert.assertEquals(name, actualRequest.getName()); + assertEquals(name, actualRequest.getName()); } @Test @SuppressWarnings("all") - public void cancelOperationExceptionTest() throws Exception { + void cancelOperationExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT); mockOperations.addException(exception); - try { - String name = "name3373707"; - - client.cancelOperation(name); - Assert.fail("No exception raised"); - } catch (InvalidArgumentException e) { - // Expected exception - } + String name = "name3373707"; + assertThrows( + InvalidArgumentException.class, + () -> { + client.cancelOperation(name); + }); } @Test @SuppressWarnings("all") - public void deleteOperationTest() { + void deleteOperationTest() { Empty expectedResponse = Empty.newBuilder().build(); mockOperations.addResponse(expectedResponse); @@ -214,31 +210,29 @@ public void deleteOperationTest() { client.deleteOperation(name); List actualRequests = mockOperations.getRequests(); - Assert.assertEquals(1, actualRequests.size()); + assertEquals(1, actualRequests.size()); DeleteOperationRequest actualRequest = (DeleteOperationRequest) actualRequests.get(0); - Assert.assertEquals(name, actualRequest.getName()); + assertEquals(name, actualRequest.getName()); } @Test @SuppressWarnings("all") - public void deleteOperationExceptionTest() throws Exception { + void deleteOperationExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT); mockOperations.addException(exception); - try { - String name = "name3373707"; - - client.deleteOperation(name); - Assert.fail("No exception raised"); - } catch (InvalidArgumentException e) { - // Expected exception - } + String name = "name3373707"; + assertThrows( + InvalidArgumentException.class, + () -> { + client.deleteOperation(name); + }); } @Test @SuppressWarnings("all") - public void waitOperationTest() { + void waitOperationTest() { String name2 = "name2-1052831874"; boolean done = true; Operation expectedResponse = Operation.newBuilder().setName(name2).setDone(done).build(); @@ -250,31 +244,29 @@ public void waitOperationTest() { WaitOperationRequest.newBuilder().setName(name).setTimeout(timeout).build(); Operation actualResponse = client.waitOperation(request); - Assert.assertEquals(expectedResponse, actualResponse); + assertEquals(expectedResponse, actualResponse); List actualRequests = mockOperations.getRequests(); - Assert.assertEquals(1, actualRequests.size()); + assertEquals(1, actualRequests.size()); WaitOperationRequest actualRequest = (WaitOperationRequest) actualRequests.get(0); - Assert.assertEquals(name, actualRequest.getName()); + assertEquals(name, actualRequest.getName()); } @Test @SuppressWarnings("all") - public void waitOperationExceptionTest() throws Exception { + void waitOperationExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT); mockOperations.addException(exception); - try { - String name = "name3373707"; - Duration timeout = Duration.newBuilder().setSeconds(5).build(); - WaitOperationRequest request = - WaitOperationRequest.newBuilder().setName(name).setTimeout(timeout).build(); - - client.waitOperation(request); - Assert.fail("No exception raised"); - } catch (InvalidArgumentException e) { - // Expected exception - } + String name = "name3373707"; + Duration timeout = Duration.newBuilder().setSeconds(5).build(); + WaitOperationRequest request = + WaitOperationRequest.newBuilder().setName(name).setTimeout(timeout).build(); + assertThrows( + InvalidArgumentException.class, + () -> { + client.waitOperation(request); + }); } } diff --git a/gax-java/gax-httpjson/BUILD.bazel b/gax-java/gax-httpjson/BUILD.bazel index 15c81e73d4..1e134e6770 100644 --- a/gax-java/gax-httpjson/BUILD.bazel +++ b/gax-java/gax-httpjson/BUILD.bazel @@ -28,8 +28,9 @@ _COMPILE_DEPS = [ ] _TEST_COMPILE_DEPS = [ - "@junit_junit//jar", + "@org_junit_jupiter_junit_jupiter_api//jar", "@org_mockito_mockito_core//jar", + "@org_mockito_mockito_junit_jupiter//jar", "@com_google_truth_truth//jar", "//gax:gax_testlib", "@com_googlecode_java_diff_utils_diffutils//jar", diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/GaxHttpJsonPropertiesTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/GaxHttpJsonPropertiesTest.java index 487605a62a..007b100577 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/GaxHttpJsonPropertiesTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/GaxHttpJsonPropertiesTest.java @@ -30,15 +30,15 @@ package com.google.api.gax.httpjson; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GaxHttpJsonPropertiesTest { +class GaxHttpJsonPropertiesTest { private static final String X_GOOG_API_CLIENT = "x-goog-api-client"; @Test - public void testDefaultHeaderPattern() { + void testDefaultHeaderPattern() { assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher("gl-java/1.8_00 gapic/1.2.3-alpha gax/1.5.0 rest/1.7.0") diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpHeadersUtilsTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpHeadersUtilsTest.java index 9c305977d5..247f2b2907 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpHeadersUtilsTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpHeadersUtilsTest.java @@ -29,19 +29,19 @@ */ package com.google.api.gax.httpjson; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import com.google.api.client.http.HttpHeaders; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class HttpHeadersUtilsTest { +class HttpHeadersUtilsTest { @Test - public void testSetHeader() { + void testSetHeader() { HttpHeaders headers = new HttpHeaders(); assertEquals(headers, HttpHeadersUtils.setHeader(headers, "Custom-Header", "CustomHeader")); @@ -105,7 +105,7 @@ public void testSetHeader() { } @Test - public void testSetHeaders() { + void testSetHeaders() { HttpHeaders headers = new HttpHeaders(); Map headersMap = @@ -120,7 +120,7 @@ public void testSetHeaders() { } @Test - public void testGetUserAgentValue() { + void testGetUserAgentValue() { Map headersMap = ImmutableMap.of( "Custom-Header", "CustomHeader", "User-Agent", "this is me", "accept", "Accept"); diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallContextTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallContextTest.java index fc872d3529..1da469cdb2 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallContextTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallContextTest.java @@ -29,10 +29,11 @@ */ package com.google.api.gax.httpjson; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; @@ -49,30 +50,24 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class HttpJsonCallContextTest { +class HttpJsonCallContextTest { @Test - public void testNullToSelfWrongType() { - try { - HttpJsonCallContext.createDefault().nullToSelf(FakeCallContext.createDefault()); - Assert.fail("HttpJsonCallContext should have thrown an exception"); - } catch (IllegalArgumentException expected) { - Truth.assertThat(expected) - .hasMessageThat() - .contains("context must be an instance of HttpJsonCallContext"); - } + void testNullToSelfWrongType() { + IllegalArgumentException actual = + assertThrows( + IllegalArgumentException.class, + () -> HttpJsonCallContext.createDefault().nullToSelf(FakeCallContext.createDefault())); + assertTrue(actual.getMessage().contains("context must be an instance of HttpJsonCallContext")); } @Test - public void testWithCredentials() { + void testWithCredentials() { Credentials credentials = Mockito.mock(Credentials.class); HttpJsonCallContext emptyContext = HttpJsonCallContext.createDefault(); assertNull(emptyContext.getCredentials()); @@ -81,7 +76,7 @@ public void testWithCredentials() { } @Test - public void testWithTransportChannel() { + void testWithTransportChannel() { ManagedHttpJsonChannel channel = Mockito.mock(ManagedHttpJsonChannel.class); HttpJsonCallContext context = @@ -92,22 +87,22 @@ public void testWithTransportChannel() { } @Test - public void testWithTransportChannelWrongType() { + void testWithTransportChannelWrongType() { try { FakeChannel channel = new FakeChannel(); HttpJsonCallContext.createDefault() .withTransportChannel(FakeTransportChannel.create(channel)); - Assert.fail("HttpJsonCallContext should have thrown an exception"); + Assertions.fail("HttpJsonCallContext should have thrown an exception"); } catch (IllegalArgumentException expected) { Truth.assertThat(expected).hasMessageThat().contains("Expected HttpJsonTransportChannel"); } } @Test - public void testMergeWrongType() { + void testMergeWrongType() { try { HttpJsonCallContext.createDefault().merge(FakeCallContext.createDefault()); - Assert.fail("HttpJsonCallContext should have thrown an exception"); + Assertions.fail("HttpJsonCallContext should have thrown an exception"); } catch (IllegalArgumentException expected) { Truth.assertThat(expected) .hasMessageThat() @@ -116,24 +111,24 @@ public void testMergeWrongType() { } @Test - public void testWithTimeout() { + void testWithTimeout() { assertNull(HttpJsonCallContext.createDefault().withTimeout(null).getTimeout()); } @Test - public void testWithNegativeTimeout() { + void testWithNegativeTimeout() { assertNull( HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(-1L)).getTimeout()); } @Test - public void testWithZeroTimeout() { + void testWithZeroTimeout() { assertNull( HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(0L)).getTimeout()); } @Test - public void testWithShorterTimeout() { + void testWithShorterTimeout() { HttpJsonCallContext ctxWithLongTimeout = HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(10)); @@ -147,7 +142,7 @@ public void testWithShorterTimeout() { } @Test - public void testWithLongerTimeout() { + void testWithLongerTimeout() { HttpJsonCallContext ctxWithShortTimeout = HttpJsonCallContext.createDefault().withTimeout(Duration.ofSeconds(5)); @@ -161,7 +156,7 @@ public void testWithLongerTimeout() { } @Test - public void testMergeWithNullTimeout() { + void testMergeWithNullTimeout() { Duration timeout = Duration.ofSeconds(10); HttpJsonCallContext baseContext = HttpJsonCallContext.createDefault().withTimeout(timeout); @@ -173,7 +168,7 @@ public void testMergeWithNullTimeout() { } @Test - public void testMergeWithTimeout() { + void testMergeWithTimeout() { Duration timeout = Duration.ofSeconds(19); HttpJsonCallContext ctx1 = HttpJsonCallContext.createDefault(); HttpJsonCallContext ctx2 = HttpJsonCallContext.createDefault().withTimeout(timeout); @@ -182,7 +177,7 @@ public void testMergeWithTimeout() { } @Test - public void testMergeWithTracer() { + void testMergeWithTracer() { ApiTracer explicitTracer = Mockito.mock(ApiTracer.class); HttpJsonCallContext ctxWithExplicitTracer = HttpJsonCallContext.createDefault().withTracer(explicitTracer); @@ -204,7 +199,7 @@ public void testMergeWithTracer() { } @Test - public void testWithRetrySettings() { + void testWithRetrySettings() { RetrySettings retrySettings = Mockito.mock(RetrySettings.class); HttpJsonCallContext emptyContext = HttpJsonCallContext.createDefault(); assertNull(emptyContext.getRetrySettings()); @@ -213,7 +208,7 @@ public void testWithRetrySettings() { } @Test - public void testWithRetryableCodes() { + void testWithRetryableCodes() { Set codes = Collections.singleton(StatusCode.Code.UNAVAILABLE); HttpJsonCallContext emptyContext = HttpJsonCallContext.createDefault(); assertNull(emptyContext.getRetryableCodes()); @@ -222,7 +217,7 @@ public void testWithRetryableCodes() { } @Test - public void testWithExtraHeaders() { + void testWithExtraHeaders() { Map> headers = ImmutableMap.of("k", Arrays.asList("v")); ApiCallContext emptyContext = HttpJsonCallContext.createDefault(); assertTrue(emptyContext.getExtraHeaders().isEmpty()); @@ -231,7 +226,7 @@ public void testWithExtraHeaders() { } @Test - public void testWithOptions() { + void testWithOptions() { ApiCallContext emptyCallContext = HttpJsonCallContext.createDefault(); ApiCallContext.Key contextKey1 = ApiCallContext.Key.create("testKey1"); ApiCallContext.Key contextKey2 = ApiCallContext.Key.create("testKey2"); @@ -249,7 +244,7 @@ public void testWithOptions() { } @Test - public void testMergeOptions() { + void testMergeOptions() { ApiCallContext emptyCallContext = HttpJsonCallContext.createDefault(); ApiCallContext.Key contextKey1 = ApiCallContext.Key.create("testKey1"); ApiCallContext.Key contextKey2 = ApiCallContext.Key.create("testKey2"); diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallableFactoryTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallableFactoryTest.java index 4d0785f242..7f317a60bf 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallableFactoryTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallableFactoryTest.java @@ -39,15 +39,12 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -@RunWith(JUnit4.class) -public class HttpJsonCallableFactoryTest { +class HttpJsonCallableFactoryTest { @Test - public void testGetSpanName() { + void testGetSpanName() { Map validNames = ImmutableMap.of( "compute.projects.disableXpnHost", SpanName.of("compute.projects", "disableXpnHost"), @@ -69,7 +66,7 @@ public void testGetSpanName() { } @Test - public void testGetSpanNameInvalid() { + void testGetSpanNameInvalid() { List invalidNames = ImmutableList.of("no_split", ".no_client"); for (String invalidName : invalidNames) { diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallImplTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallImplTest.java index 0355dd0d4b..e65c9d9758 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallImplTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallImplTest.java @@ -39,14 +39,14 @@ import java.util.concurrent.Executor; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class HttpJsonClientCallImplTest { +@ExtendWith(MockitoExtension.class) +class HttpJsonClientCallImplTest { @Mock private ApiMethodDescriptor apiMethodDescriptor; @Mock private HttpResponseParser httpResponseParser; @Mock private HttpJsonCallOptions httpJsonCallOptions; @@ -56,7 +56,7 @@ public class HttpJsonClientCallImplTest { @Mock private HttpJsonClientCall.Listener listener; @Test - public void responseReceived_noCancellationTask() { + void responseReceived_noCancellationTask() { ScheduledThreadPoolExecutor deadlineSchedulerExecutor = new ScheduledThreadPoolExecutor(1); // Null timeout means no timeout task created Mockito.when(httpJsonCallOptions.getTimeout()).thenReturn(null); @@ -86,8 +86,7 @@ public void responseReceived_noCancellationTask() { } @Test - public void responseReceived_cancellationTaskExists_isCancelledProperly() - throws InterruptedException { + void responseReceived_cancellationTaskExists_isCancelledProperly() throws InterruptedException { ScheduledThreadPoolExecutor deadlineSchedulerExecutor = new ScheduledThreadPoolExecutor(1); // SetRemoveOnCancelPolicy will immediately remove the task from the work queue // when the task is cancelled diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallsTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallsTest.java index c4cdcf1390..7e2d9cb946 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallsTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientCallsTest.java @@ -30,7 +30,7 @@ package com.google.api.gax.httpjson; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.gax.rpc.EndpointContext; import com.google.api.gax.rpc.StatusCode; @@ -38,14 +38,11 @@ import com.google.auth.Credentials; import com.google.auth.Retryable; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -@RunWith(JUnit4.class) -public class HttpJsonClientCallsTest { +class HttpJsonClientCallsTest { // Auth Library's GoogleAuthException is package-private. Copy basic functionality for tests private static class GoogleAuthException extends IOException implements Retryable { @@ -74,8 +71,8 @@ public int getRetryCount() { private HttpJsonCallOptions callOptions; private HttpJsonCallContext callContext; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { credentials = Mockito.mock(Credentials.class); endpointContext = Mockito.mock(EndpointContext.class); mockChannel = Mockito.mock(HttpJsonChannel.class); @@ -95,14 +92,14 @@ public void setUp() throws IOException { } @Test - public void testValidUniverseDomain() { + void testValidUniverseDomain() { HttpJsonClientCalls.newCall(descriptor, callContext); Mockito.verify(mockChannel, Mockito.times(1)).newCall(descriptor, callOptions); } // This test is when the universe domain does not match @Test - public void testInvalidUniverseDomain() throws IOException { + void testInvalidUniverseDomain() throws IOException { Mockito.doThrow( new UnauthenticatedException( null, HttpJsonStatusCode.of(StatusCode.Code.UNAUTHENTICATED), false)) @@ -121,7 +118,7 @@ public void testInvalidUniverseDomain() throws IOException { // This test is when the MDS is unable to return a valid universe domain @Test - public void testUniverseDomainNotReady_shouldRetry() throws IOException { + void testUniverseDomainNotReady_shouldRetry() throws IOException { Mockito.doThrow(new GoogleAuthException(true)) .when(endpointContext) .validateUniverseDomain( diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientInterceptorTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientInterceptorTest.java index 463b76112b..dc5844616d 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientInterceptorTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonClientInterceptorTest.java @@ -46,18 +46,15 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class HttpJsonClientInterceptorTest { +class HttpJsonClientInterceptorTest { private static class CapturingClientInterceptor implements HttpJsonClientInterceptor { // Manually capturing arguments instead of using Mockito. This is intentional, as this @@ -143,7 +140,7 @@ public void onClose(int statusCode, HttpJsonMetadata trailers) { private CapturingClientInterceptor interceptor; private ManagedHttpJsonChannel channel; - @BeforeClass + @BeforeAll public static void initialize() { executorService = Executors.newFixedThreadPool( @@ -155,13 +152,13 @@ public static void initialize() { }); } - @AfterClass + @AfterAll public static void destroy() { executorService.shutdownNow(); } - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { interceptor = new CapturingClientInterceptor(); channel = InstantiatingHttpJsonChannelProvider.newBuilder() @@ -175,13 +172,13 @@ public void setUp() throws IOException { .getManagedChannel(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { MOCK_SERVICE.reset(); } @Test - public void testCustomInterceptor() throws ExecutionException, InterruptedException, IOException { + void testCustomInterceptor() throws ExecutionException, InterruptedException, IOException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectCallableTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectCallableTest.java index 619052744a..0c14779bc8 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectCallableTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectCallableTest.java @@ -49,18 +49,15 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class HttpJsonDirectCallableTest { +class HttpJsonDirectCallableTest { private static final ApiMethodDescriptor FAKE_METHOD_DESCRIPTOR = ApiMethodDescriptor.newBuilder() @@ -111,7 +108,7 @@ public class HttpJsonDirectCallableTest { private static HttpJsonCallContext defaultCallContext; - @BeforeClass + @BeforeAll public static void initialize() throws IOException { executorService = Executors.newFixedThreadPool( @@ -133,18 +130,18 @@ public static void initialize() throws IOException { .withEndpointContext(endpointContext); } - @AfterClass + @AfterAll public static void destroy() { executorService.shutdownNow(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { MOCK_SERVICE.reset(); } @Test - public void testSuccessfulUnaryResponse() throws ExecutionException, InterruptedException { + void testSuccessfulUnaryResponse() throws ExecutionException, InterruptedException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); @@ -173,7 +170,7 @@ public void testSuccessfulUnaryResponse() throws ExecutionException, Interrupted * @throws ExecutionException */ @Test - public void testSuccessfulMultipleResponsesForUnaryCall() + void testSuccessfulMultipleResponsesForUnaryCall() throws InterruptedException, ExecutionException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); @@ -203,8 +200,7 @@ public void testSuccessfulMultipleResponsesForUnaryCall() * @throws ExecutionException */ @Test - public void testErrorMultipleResponsesForUnaryCall() - throws InterruptedException, ExecutionException { + void testErrorMultipleResponsesForUnaryCall() throws InterruptedException, ExecutionException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); @@ -231,7 +227,7 @@ public void testErrorMultipleResponsesForUnaryCall() * @throws InterruptedException */ @Test - public void testErrorUnaryResponse() throws InterruptedException { + void testErrorUnaryResponse() throws InterruptedException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); @@ -242,7 +238,7 @@ public void testErrorUnaryResponse() throws InterruptedException { try { callable.futureCall(createTestMessage(2), defaultCallContext).get(); - Assert.fail("No exception raised"); + Assertions.fail("No exception raised"); } catch (ExecutionException e) { HttpResponseException respExp = (HttpResponseException) e.getCause(); assertThat(respExp.getStatusCode()).isEqualTo(400); @@ -258,7 +254,7 @@ public void testErrorUnaryResponse() throws InterruptedException { * @throws InterruptedException */ @Test - public void testErrorNullContentSuccessfulResponse() throws InterruptedException { + void testErrorNullContentSuccessfulResponse() throws InterruptedException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); @@ -266,7 +262,7 @@ public void testErrorNullContentSuccessfulResponse() throws InterruptedException try { callable.futureCall(createTestMessage(2), defaultCallContext).get(); - Assert.fail("No exception raised"); + Assertions.fail("No exception raised"); } catch (ExecutionException e) { HttpJsonStatusRuntimeException respExp = (HttpJsonStatusRuntimeException) e.getCause(); assertThat(respExp.getStatusCode()).isEqualTo(200); @@ -282,7 +278,7 @@ public void testErrorNullContentSuccessfulResponse() throws InterruptedException * @throws InterruptedException */ @Test - public void testErrorNullContentFailedResponse() throws InterruptedException { + void testErrorNullContentFailedResponse() throws InterruptedException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); @@ -290,7 +286,7 @@ public void testErrorNullContentFailedResponse() throws InterruptedException { try { callable.futureCall(createTestMessage(2), defaultCallContext).get(); - Assert.fail("No exception raised"); + Assertions.fail("No exception raised"); } catch (ExecutionException e) { HttpResponseException respExp = (HttpResponseException) e.getCause(); assertThat(respExp.getStatusCode()).isEqualTo(400); @@ -304,7 +300,7 @@ public void testErrorNullContentFailedResponse() throws InterruptedException { * @throws InterruptedException */ @Test - public void testErrorNon2xxOr4xxResponse() throws InterruptedException { + void testErrorNon2xxOr4xxResponse() throws InterruptedException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); @@ -315,7 +311,7 @@ public void testErrorNon2xxOr4xxResponse() throws InterruptedException { try { callable.futureCall(createTestMessage(2), defaultCallContext).get(); - Assert.fail("No exception raised"); + Assertions.fail("No exception raised"); } catch (ExecutionException e) { HttpResponseException respExp = (HttpResponseException) e.getCause(); assertThat(respExp.getStatusCode()).isEqualTo(500); @@ -331,7 +327,7 @@ public void testErrorNon2xxOr4xxResponse() throws InterruptedException { * @throws InterruptedException */ @Test - public void testDeadlineExceededResponse() throws InterruptedException { + void testDeadlineExceededResponse() throws InterruptedException { HttpJsonDirectCallable callable = new HttpJsonDirectCallable<>(FAKE_METHOD_DESCRIPTOR); @@ -342,7 +338,7 @@ public void testDeadlineExceededResponse() throws InterruptedException { try { callable.futureCall(createTestMessage(10), callContext).get(); - Assert.fail("No exception raised"); + Assertions.fail("No exception raised"); } catch (ExecutionException e) { HttpJsonStatusRuntimeException respExp = (HttpJsonStatusRuntimeException) e.getCause(); assertThat(respExp.getStatusCode()).isEqualTo(504); diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectServerStreamingCallableTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectServerStreamingCallableTest.java index 3fc1724439..5cae0fda31 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectServerStreamingCallableTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonDirectServerStreamingCallableTest.java @@ -61,17 +61,14 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.threeten.bp.Duration; -@RunWith(JUnit4.class) -public class HttpJsonDirectServerStreamingCallableTest { +class HttpJsonDirectServerStreamingCallableTest { private static final Color DEFAULT_REQUEST = Color.newBuilder().setRed(0.5f).build(); private static final Color ASYNC_REQUEST = DEFAULT_REQUEST.toBuilder().setGreen(1000).build(); private static final Color ERROR_REQUEST = Color.newBuilder().setRed(-1).build(); @@ -89,12 +86,12 @@ public class HttpJsonDirectServerStreamingCallableTest { private MockHttpService mockService; ApiMethodDescriptor methodServerStreamingRecognize; - @Before - public void initialize() throws IOException { + @BeforeEach + void initialize() throws IOException { initialize(Duration.ofSeconds(30)); } - public void initialize(Duration timeout) throws IOException { + void initialize(Duration timeout) throws IOException { this.methodServerStreamingRecognize = ApiMethodDescriptor.newBuilder() .setFullMethodName("google.cloud.v1.Fake/ServerStreamingRecognize") @@ -162,14 +159,14 @@ public void initialize(Duration timeout) throws IOException { clientContext); } - @After - public void destroy() throws InterruptedException { + @AfterEach + void destroy() throws InterruptedException { executorService.shutdown(); channel.shutdown(); } @Test - public void testBadContext() { + void testBadContext() { mockService.addResponse(new Money[] {DEFAULT_RESPONSE}); // Create a local callable with a bad context ServerStreamingCallable streamingCallable = @@ -186,7 +183,7 @@ public void testBadContext() { MoneyObserver observer = new MoneyObserver(true, latch); try { streamingCallable.call(DEFAULT_REQUEST, observer); - Assert.fail("Callable should have thrown an exception"); + Assertions.fail("Callable should have thrown an exception"); } catch (IllegalArgumentException expected) { Truth.assertThat(expected) .hasMessageThat() @@ -195,7 +192,7 @@ public void testBadContext() { } @Test - public void testServerStreamingStart() throws InterruptedException { + void testServerStreamingStart() throws InterruptedException { mockService.addResponse(new Money[] {DEFAULT_RESPONSE}); CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(true, latch); @@ -206,7 +203,7 @@ public void testServerStreamingStart() throws InterruptedException { } @Test - public void testServerStreaming() throws InterruptedException { + void testServerStreaming() throws InterruptedException { mockService.addResponse(new Money[] {DEFAULT_RESPONSE, DEFAULTER_RESPONSE}); CountDownLatch latch = new CountDownLatch(3); MoneyObserver moneyObserver = new MoneyObserver(true, latch); @@ -220,7 +217,7 @@ public void testServerStreaming() throws InterruptedException { } @Test - public void testManualFlowControl() throws Exception { + void testManualFlowControl() throws Exception { mockService.addResponse(new Money[] {DEFAULT_RESPONSE}); CountDownLatch latch = new CountDownLatch(2); MoneyObserver moneyObserver = new MoneyObserver(false, latch); @@ -240,7 +237,7 @@ public void testManualFlowControl() throws Exception { } @Test - public void testCancelClientCall() throws Exception { + void testCancelClientCall() throws Exception { mockService.addResponse(new Money[] {DEFAULT_RESPONSE}); CountDownLatch latch = new CountDownLatch(1); MoneyObserver moneyObserver = new MoneyObserver(false, latch); @@ -256,7 +253,7 @@ public void testCancelClientCall() throws Exception { } @Test - public void testOnResponseError() throws Throwable { + void testOnResponseError() throws Throwable { mockService.addException(404, new RuntimeException("some error")); CountDownLatch latch = new CountDownLatch(1); @@ -281,7 +278,7 @@ public void testOnResponseError() throws Throwable { } @Test - public void testObserverErrorCancelsCall() throws Throwable { + void testObserverErrorCancelsCall() throws Throwable { mockService.addResponse(new Money[] {DEFAULT_RESPONSE}); final RuntimeException expectedCause = new RuntimeException("some error"); final SettableApiFuture actualErrorF = SettableApiFuture.create(); @@ -321,7 +318,7 @@ protected void onCompleteImpl() { } @Test - public void testBlockingServerStreaming() { + void testBlockingServerStreaming() { mockService.addResponse(new Money[] {DEFAULT_RESPONSE}); Color request = Color.newBuilder().setRed(0.5f).build(); ServerStream response = streamingCallable.call(request); @@ -333,7 +330,7 @@ public void testBlockingServerStreaming() { // This test ensures that the server-side streaming does not exceed the timeout value @Test - public void testDeadlineExceededServerStreaming() throws InterruptedException, IOException { + void testDeadlineExceededServerStreaming() throws InterruptedException, IOException { // set a low timeout to trigger deadline-exceeded sooner initialize(Duration.ofSeconds(1)); diff --git a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonLongRunningClientTest.java b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonLongRunningClientTest.java index 702f327a6b..0858ae350c 100644 --- a/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonLongRunningClientTest.java +++ b/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonLongRunningClientTest.java @@ -30,7 +30,7 @@ package com.google.api.gax.httpjson; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -42,17 +42,17 @@ import com.google.common.truth.Truth; import com.google.protobuf.Field; import com.google.protobuf.Option; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class HttpJsonLongRunningClientTest { +class HttpJsonLongRunningClientTest { private OperationSnapshotFactory operationSnapFact; private PollingRequestFactory