Java Code Examples for org.mockito.ArgumentCaptor
The following examples show how to use
org.mockito.ArgumentCaptor.
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: java-technology-stack Author: codeEngraver File: StompBrokerRelayMessageHandlerTests.java License: MIT License | 7 votes |
@Test public void systemSubscription() throws Exception { MessageHandler handler = mock(MessageHandler.class); this.brokerRelay.setSystemSubscriptions(Collections.singletonMap("/topic/foo", handler)); this.brokerRelay.start(); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED); accessor.setLeaveMutable(true); MessageHeaders headers = accessor.getMessageHeaders(); this.tcpClient.handleMessage(MessageBuilder.createMessage(new byte[0], headers)); assertEquals(2, this.tcpClient.getSentMessages().size()); assertEquals(StompCommand.CONNECT, this.tcpClient.getSentHeaders(0).getCommand()); assertEquals(StompCommand.SUBSCRIBE, this.tcpClient.getSentHeaders(1).getCommand()); assertEquals("/topic/foo", this.tcpClient.getSentHeaders(1).getDestination()); Message<byte[]> message = message(StompCommand.MESSAGE, null, null, "/topic/foo"); this.tcpClient.handleMessage(message); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); verify(handler).handleMessage(captor.capture()); assertSame(message, captor.getValue()); }
Example #2
Source Project: Moss Author: SpringCloud File: MailNotifierTest.java License: Apache License 2.0 | 6 votes |
@Test public void should_send_mail_using_custom_template_with_additional_properties() throws IOException, MessagingException { notifier.setTemplate("/de/codecentric/boot/admin/server/notify/custom-mail.html"); notifier.getAdditionalProperties().put("customProperty", "HELLO WORLD!"); StepVerifier.create(notifier.notify( new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofDown()))) .verifyComplete(); ArgumentCaptor<MimeMessage> mailCaptor = ArgumentCaptor.forClass(MimeMessage.class); verify(sender).send(mailCaptor.capture()); MimeMessage mail = mailCaptor.getValue(); String body = extractBody(mail.getDataHandler()); assertThat(body).isEqualTo(loadExpectedBody("expected-custom-mail")); }
Example #3
Source Project: besu Author: hyperledger File: BesuCommandTest.java License: Apache License 2.0 | 6 votes |
private void networkValuesCanBeOverridden(final String network) throws Exception { parseCommand( "--network", network, "--network-id", "1234567", "--bootnodes", String.join(",", validENodeStrings)); final ArgumentCaptor<EthNetworkConfig> networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); assertThat(networkArg.getValue().getBootNodes()) .isEqualTo( Stream.of(validENodeStrings).map(EnodeURL::fromString).collect(Collectors.toList())); assertThat(networkArg.getValue().getNetworkId()).isEqualTo(1234567); assertThat(commandOutput.toString()).isEmpty(); assertThat(commandErrorOutput.toString()).isEmpty(); }
Example #4
Source Project: grpc-nebula-java Author: grpc-nebula File: DeadlineTest.java License: Apache License 2.0 | 6 votes |
@Test public void runOnAlreadyExpiredIsExecutedOnExecutor() throws Exception { Deadline base = Deadline.after(0, TimeUnit.MICROSECONDS, ticker); ScheduledExecutorService mockScheduler = mock(ScheduledExecutorService.class); final AtomicBoolean executed = new AtomicBoolean(); Future<?> unused = base.runOnExpiration( new Runnable() { @Override public void run() { executed.set(true); } }, mockScheduler); assertFalse(executed.get()); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); verify(mockScheduler).schedule(runnableCaptor.capture(), eq(0L), eq(TimeUnit.NANOSECONDS)); runnableCaptor.getValue().run(); assertTrue(executed.get()); }
Example #5
Source Project: besu Author: hyperledger File: BesuCommandTest.java License: Apache License 2.0 | 6 votes |
@Test public void privacyMultiTenancyIsConfiguredWhenConfiguredWithNecessaryOptions() { parseCommand( "--privacy-enabled", "--rpc-http-authentication-enabled", "--privacy-multi-tenancy-enabled", "--rpc-http-authentication-jwt-public-key-file", "/non/existent/file"); final ArgumentCaptor<PrivacyParameters> privacyParametersArgumentCaptor = ArgumentCaptor.forClass(PrivacyParameters.class); verify(mockControllerBuilder).privacyParameters(privacyParametersArgumentCaptor.capture()); verify(mockControllerBuilder).build(); assertThat(privacyParametersArgumentCaptor.getValue().isMultiTenancyEnabled()).isTrue(); }
Example #6
Source Project: grpc-nebula-java Author: grpc-nebula File: DeadlineTest.java License: Apache License 2.0 | 6 votes |
@Test public void runOnEventualExpirationIsExecuted() throws Exception { Deadline base = Deadline.after(50, TimeUnit.MICROSECONDS, ticker); ScheduledExecutorService mockScheduler = mock(ScheduledExecutorService.class); final AtomicBoolean executed = new AtomicBoolean(); Future<?> unused = base.runOnExpiration( new Runnable() { @Override public void run() { executed.set(true); } }, mockScheduler); assertFalse(executed.get()); ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class); verify(mockScheduler).schedule(runnableCaptor.capture(), eq(50000L), eq(TimeUnit.NANOSECONDS)); runnableCaptor.getValue().run(); assertTrue(executed.get()); }
Example #7
Source Project: grpc-nebula-java Author: grpc-nebula File: AbstractClientStreamTest.java License: Apache License 2.0 | 6 votes |
@Test public void trailerNotOkWithTruncatedMessage() { AbstractClientStream stream = new BaseAbstractClientStream(allocator, statsTraceCtx, transportTracer); stream.start(mockListener); stream.transportState().requestMessagesFromDeframer(1); stream.transportState().deframe(ReadableBuffers.wrap(new byte[] {0, 0, 0, 0, 2, 1})); stream.transportState().inboundTrailersReceived( new Metadata(), Status.DATA_LOSS.withDescription("data___loss")); ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class); verify(mockListener) .closed(statusCaptor.capture(), any(RpcProgress.class), any(Metadata.class)); assertSame(Status.Code.DATA_LOSS, statusCaptor.getValue().getCode()); assertEquals("data___loss", statusCaptor.getValue().getDescription()); }
Example #8
Source Project: data-highway Author: HotelsDotCom File: KafkaBrokerMonitorTest.java License: Apache License 2.0 | 6 votes |
@Test public void testName() throws Exception { doReturn(Collections.singletonList("0")).when(client).getBrokerIds(); doReturn(new Properties()).when(client).getConfig("0"); underTest.checkAndUpdateBrokers(); ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class); verify(client).changeConfig(eq("0"), captor.capture()); Properties config = captor.getValue(); assertThat(config.size(), is(2)); assertThat(config.getProperty("leader.replication.throttled.rate"), is("1")); assertThat(config.getProperty("follower.replication.throttled.rate"), is("2")); }
Example #9
Source Project: grpc-nebula-java Author: grpc-nebula File: NettyClientHandlerTest.java License: Apache License 2.0 | 6 votes |
@Test public void inboundShouldForwardToStream() throws Exception { createStream(); // Read a headers frame first. Http2Headers headers = new DefaultHttp2Headers().status(STATUS_OK) .set(CONTENT_TYPE_HEADER, CONTENT_TYPE_GRPC) .set(as("magic"), as("value")); ByteBuf headersFrame = headersFrame(3, headers); channelRead(headersFrame); ArgumentCaptor<Metadata> captor = ArgumentCaptor.forClass(Metadata.class); verify(streamListener).headersRead(captor.capture()); assertEquals("value", captor.getValue().get(Metadata.Key.of("magic", Metadata.ASCII_STRING_MARSHALLER))); streamTransportState.requestMessagesFromDeframer(1); // Create a data frame and then trigger the handler to read it. ByteBuf frame = grpcDataFrame(3, false, contentAsArray()); channelRead(frame); InputStream message = streamListenerMessageQueue.poll(); assertArrayEquals(ByteBufUtil.getBytes(content()), ByteStreams.toByteArray(message)); message.close(); assertNull("no additional message expected", streamListenerMessageQueue.poll()); }
Example #10
Source Project: data-highway Author: HotelsDotCom File: ConsumerRecordWriterTest.java License: Apache License 2.0 | 6 votes |
@Test public void write_Close() throws IOException { when(outputStreamFactory.create(LOCATION)).thenReturn(abortableOutputStream); ArgumentCaptor<OutputStream> captor = ArgumentCaptor.forClass(OutputStream.class); when(recordWriterFactory.create(eq(schema1), captor.capture())).thenReturn(recordWriter); underTest.getByteCounter().getAndAdd(1L); // fake some written bytes ConsumerRecord<Void, Record> record = record(schema1, "foo", 1, 10); underTest.write(record); underTest.close(); verify(recordWriter).write(record.value()); assertThat(underTest.getRecordCounter().get(), is(0L)); verify(metrics).consumedBytes(10); verify(metrics).offsetHighwaterMark(0, 1); verify(metrics).uploadedBytes(1L); verify(metrics).uploadedEvents(1L); assertThat(writers.size(), is(0)); }
Example #11
Source Project: vertx-spring-boot Author: snowdrop File: VertxWebSocketClientTest.java License: Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("unchecked") public void shouldAdaptHeaders() { HttpHeaders originalHeaders = new HttpHeaders(); originalHeaders.put("key1", Arrays.asList("value1", "value2")); originalHeaders.add("key2", "value3"); webSocketClient.execute(TEST_URI, originalHeaders, session -> Mono.empty()) .subscribe(); ArgumentCaptor<VertxHttpHeaders> headersCaptor = ArgumentCaptor.forClass(VertxHttpHeaders.class); verify(mockHttpClient).websocket(anyInt(), anyString(), anyString(), headersCaptor.capture(), any(Handler.class), any(Handler.class)); VertxHttpHeaders actualHeaders = headersCaptor.getValue(); assertThat(actualHeaders.getAll("key1")).isEqualTo(originalHeaders.get("key1")); assertThat(actualHeaders.getAll("key2")).isEqualTo(originalHeaders.get("key2")); }
Example #12
Source Project: dynein Author: airbnb File: AsyncSqsClientImplTest.java License: Apache License 2.0 | 6 votes |
@Test public void testAddWithDelay() { urlSetup("testQueue", "testUrl"); queueAddSetup(); sentRequest = ArgumentCaptor.forClass(SendMessageRequest.class); CompletableFuture<Void> delay = asyncClient.add("test", "testQueue", 10); verify(awsAsyncSqsClient).sendMessage(sentRequest.capture()); assertEquals(sentRequest.getValue().messageBody(), "test"); assertEquals(sentRequest.getValue().queueUrl(), "testUrl"); assertEquals(sentRequest.getValue().delaySeconds(), new Integer(10)); verify(awsAsyncSqsClient, times(1)).sendMessage(any(SendMessageRequest.class)); assertNull(delay.join()); }
Example #13
Source Project: client-encryption-java Author: Mastercard File: HttpExecuteFieldLevelEncryptionInterceptorTest.java License: MIT License | 6 votes |
@Test public void testIntercept_ShouldEncryptRequestPayloadAndUpdateContentLengthHeader() throws Exception { // GIVEN FieldLevelEncryptionConfig config = getTestFieldLevelEncryptionConfigBuilder() .withEncryptionPath("$.foo", "$.encryptedFoo") .build(); HttpRequest request = mock(HttpRequest.class); HttpHeaders httpHeaders = new HttpHeaders(); when(request.getContent()).thenReturn(new ByteArrayContent(JSON_TYPE, "{\"foo\":\"bar\"}".getBytes())); when(request.getHeaders()).thenReturn(httpHeaders); // WHEN HttpExecuteFieldLevelEncryptionInterceptor instanceUnderTest = new HttpExecuteFieldLevelEncryptionInterceptor(config); instanceUnderTest.intercept(request); // THEN ArgumentCaptor<HttpContent> contentCaptor = ArgumentCaptor.forClass(HttpContent.class); verify(request).setContent(contentCaptor.capture()); ByteArrayOutputStream encryptedPayloadStream = new ByteArrayOutputStream(); contentCaptor.getValue().writeTo(encryptedPayloadStream); String encryptedPayload = encryptedPayloadStream.toString(StandardCharsets.UTF_8.name()); Assert.assertFalse(encryptedPayload.contains("foo")); Assert.assertTrue(encryptedPayload.contains("encryptedFoo")); assertEquals(encryptedPayload.length(), httpHeaders.getContentLength().intValue()); }
Example #14
Source Project: java-technology-stack Author: codeEngraver File: SubscriptionMethodReturnValueHandlerTests.java License: MIT License | 6 votes |
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void testHeadersPassedToMessagingTemplate() throws Exception { String sessionId = "sess1"; String subscriptionId = "subs1"; String destination = "/dest"; Message<?> inputMessage = createInputMessage(sessionId, subscriptionId, destination, null); MessageSendingOperations messagingTemplate = Mockito.mock(MessageSendingOperations.class); SubscriptionMethodReturnValueHandler handler = new SubscriptionMethodReturnValueHandler(messagingTemplate); handler.handleReturnValue(PAYLOAD, this.subscribeEventReturnType, inputMessage); ArgumentCaptor<MessageHeaders> captor = ArgumentCaptor.forClass(MessageHeaders.class); verify(messagingTemplate).convertAndSend(eq("/dest"), eq(PAYLOAD), captor.capture()); SimpMessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(captor.getValue(), SimpMessageHeaderAccessor.class); assertNotNull(headerAccessor); assertTrue(headerAccessor.isMutable()); assertEquals(sessionId, headerAccessor.getSessionId()); assertEquals(subscriptionId, headerAccessor.getSubscriptionId()); assertEquals(this.subscribeEventReturnType, headerAccessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER)); }
Example #15
Source Project: grpc-nebula-java Author: grpc-nebula File: ServerCallImplTest.java License: Apache License 2.0 | 6 votes |
private void sendMessage_serverSendsOne_closeOnSecondCall( MethodDescriptor<Long, Long> method) { ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<Long, Long>( stream, method, requestHeaders, context, DecompressorRegistry.getDefaultInstance(), CompressorRegistry.getDefaultInstance(), serverCallTracer); serverCall.sendHeaders(new Metadata()); serverCall.sendMessage(1L); verify(stream, times(1)).writeMessage(any(InputStream.class)); verify(stream, never()).close(any(Status.class), any(Metadata.class)); // trying to send a second message causes gRPC to close the underlying stream serverCall.sendMessage(1L); verify(stream, times(1)).writeMessage(any(InputStream.class)); ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class); verify(stream, times(1)).cancel(statusCaptor.capture()); assertEquals(Status.Code.INTERNAL, statusCaptor.getValue().getCode()); assertEquals(ServerCallImpl.TOO_MANY_RESPONSES, statusCaptor.getValue().getDescription()); }
Example #16
Source Project: jsonschema-generator Author: victools File: SwaggerModuleTest.java License: Apache License 2.0 | 6 votes |
@Test @Parameters public void testDescriptionResolver(String fieldName, boolean asContainerItem, String expectedMemberDescription, String expectedTypeDescription) { new SwaggerModule().applyToConfigBuilder(this.configBuilder); TestType testType = new TestType(TestClassForDescription.class); FieldScope field = testType.getMemberField(fieldName); if (asContainerItem) { field = field.asFakeContainerItemScope(); } ArgumentCaptor<ConfigFunction<FieldScope, String>> memberCaptor = ArgumentCaptor.forClass(ConfigFunction.class); Mockito.verify(this.fieldConfigPart).withDescriptionResolver(memberCaptor.capture()); String memberDescription = memberCaptor.getValue().apply(field); Assert.assertEquals(expectedMemberDescription, memberDescription); ArgumentCaptor<ConfigFunction<TypeScope, String>> typeCaptor = ArgumentCaptor.forClass(ConfigFunction.class); Mockito.verify(this.typesInGeneralConfigPart).withDescriptionResolver(typeCaptor.capture()); TypeScope scope = Mockito.mock(TypeScope.class); Mockito.when(scope.getType()).thenReturn(field.getType()); String typeDescription = typeCaptor.getValue().apply(scope); Assert.assertEquals(expectedTypeDescription, typeDescription); }
Example #17
Source Project: kogito-runtimes Author: kiegroup File: DecisionTracingListenerTest.java License: Apache License 2.0 | 6 votes |
@Test void test_Listener_MockedEvents_Working() { DMNContextImpl context = new DMNContextImpl(); DecisionExecutionIdUtils.inject(context, () -> TEST_EXECUTION_ID_1); DMNResultImpl result = new DMNResultImpl(new DMNModelImpl()); result.setContext(context); BeforeEvaluateAllEvent beforeEvent = new MockBeforeEvaluateAllEvent(MOCKED_MODEL_NAMESPACE, MOCKED_MODEL_NAME, result); AfterEvaluateAllEvent afterEvent = new MockAfterEvaluateAllEvent(MOCKED_MODEL_NAMESPACE, MOCKED_MODEL_NAME, result); Consumer<EvaluateEvent> eventConsumer = mock(Consumer.class); DecisionTracingListener listener = new DecisionTracingListener(eventConsumer); listener.beforeEvaluateAll(beforeEvent); listener.afterEvaluateAll(afterEvent); ArgumentCaptor<EvaluateEvent> eventCaptor = ArgumentCaptor.forClass(EvaluateEvent.class); verify(eventConsumer, times(2)).accept(eventCaptor.capture()); assertEvaluateAllEvents(eventCaptor.getAllValues(), MOCKED_MODEL_NAMESPACE, MOCKED_MODEL_NAME, TEST_EXECUTION_ID_1); }
Example #18
Source Project: grpc-nebula-java Author: grpc-nebula File: NettyServerStreamTest.java License: Apache License 2.0 | 6 votes |
@Test public void writeMessageShouldSendResponse() throws Exception { ListMultimap<CharSequence, CharSequence> expectedHeaders = ImmutableListMultimap.copyOf(new DefaultHttp2Headers() .status(Utils.STATUS_OK) .set(Utils.CONTENT_TYPE_HEADER, Utils.CONTENT_TYPE_GRPC)); stream.writeHeaders(new Metadata()); ArgumentCaptor<SendResponseHeadersCommand> sendHeadersCap = ArgumentCaptor.forClass(SendResponseHeadersCommand.class); verify(writeQueue).enqueue(sendHeadersCap.capture(), eq(true)); SendResponseHeadersCommand sendHeaders = sendHeadersCap.getValue(); assertThat(sendHeaders.stream()).isSameAs(stream.transportState()); assertThat(ImmutableListMultimap.copyOf(sendHeaders.headers())) .containsExactlyEntriesIn(expectedHeaders); assertThat(sendHeaders.endOfStream()).isFalse(); byte[] msg = smallMessage(); stream.writeMessage(new ByteArrayInputStream(msg)); stream.flush(); verify(writeQueue).enqueue( eq(new SendGrpcFrameCommand(stream.transportState(), messageFrame(MESSAGE), false)), eq(true)); }
Example #19
Source Project: sdn-rx Author: neo4j File: TransactionHandlingTest.java License: Apache License 2.0 | 6 votes |
@Test void shouldCallCloseOnSession() { ArgumentCaptor<SessionConfig> configArgumentCaptor = ArgumentCaptor.forClass(SessionConfig.class); when(driver.session(any(SessionConfig.class))).thenReturn(session); // Make template acquire session DefaultNeo4jClient neo4jClient = new DefaultNeo4jClient(driver); try (DefaultNeo4jClient.AutoCloseableQueryRunner s = neo4jClient.getQueryRunner("aDatabase")) { s.run("MATCH (n) RETURN n"); } verify(driver).session(configArgumentCaptor.capture()); SessionConfig sessionConfig = configArgumentCaptor.getValue(); assertThat(sessionConfig.database()).isPresent().contains("aDatabase"); verify(session).run(any(String.class)); verify(session).close(); verifyNoMoreInteractions(driver, session, transaction); }
Example #20
Source Project: grpc-nebula-java Author: grpc-nebula File: NettyServerStreamTest.java License: Apache License 2.0 | 6 votes |
@Test public void writeHeadersShouldSendHeaders() throws Exception { Metadata headers = new Metadata(); ListMultimap<CharSequence, CharSequence> expectedHeaders = ImmutableListMultimap.copyOf(Utils.convertServerHeaders(headers)); stream().writeHeaders(headers); ArgumentCaptor<SendResponseHeadersCommand> sendHeadersCap = ArgumentCaptor.forClass(SendResponseHeadersCommand.class); verify(writeQueue).enqueue(sendHeadersCap.capture(), eq(true)); SendResponseHeadersCommand sendHeaders = sendHeadersCap.getValue(); assertThat(sendHeaders.stream()).isSameAs(stream.transportState()); assertThat(ImmutableListMultimap.copyOf(sendHeaders.headers())) .containsExactlyEntriesIn(expectedHeaders); assertThat(sendHeaders.endOfStream()).isFalse(); }
Example #21
Source Project: grpc-nebula-java Author: grpc-nebula File: RetriableStreamTest.java License: Apache License 2.0 | 6 votes |
@Test public void throttledStream_FailWithRetriableStatusCode_WithoutPushback() { Throttle throttle = new Throttle(4f, 0.8f); RetriableStream<String> retriableStream = newThrottledRetriableStream(throttle); ClientStream mockStream = mock(ClientStream.class); doReturn(mockStream).when(retriableStreamRecorder).newSubstream(anyInt()); retriableStream.start(masterListener); ArgumentCaptor<ClientStreamListener> sublistenerCaptor = ArgumentCaptor.forClass(ClientStreamListener.class); verify(mockStream).start(sublistenerCaptor.capture()); // mimic some other call in the channel triggers a throttle countdown assertTrue(throttle.onQualifiedFailureThenCheckIsAboveThreshold()); // count = 3 sublistenerCaptor.getValue().closed(Status.fromCode(RETRIABLE_STATUS_CODE_1), new Metadata()); verify(retriableStreamRecorder).postCommit(); assertFalse(throttle.isAboveThreshold()); // count = 2 }
Example #22
Source Project: grpc-nebula-java Author: grpc-nebula File: RetriableStreamTest.java License: Apache License 2.0 | 6 votes |
@Test public void headersRead_cancel() { ClientStream mockStream1 = mock(ClientStream.class); doReturn(mockStream1).when(retriableStreamRecorder).newSubstream(0); InOrder inOrder = inOrder(retriableStreamRecorder); retriableStream.start(masterListener); ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 = ArgumentCaptor.forClass(ClientStreamListener.class); verify(mockStream1).start(sublistenerCaptor1.capture()); sublistenerCaptor1.getValue().headersRead(new Metadata()); inOrder.verify(retriableStreamRecorder).postCommit(); retriableStream.cancel(Status.CANCELLED); inOrder.verify(retriableStreamRecorder, never()).postCommit(); }
Example #23
Source Project: grpc-nebula-java Author: grpc-nebula File: CallCredentials2ApplyingTest.java License: Apache License 2.0 | 6 votes |
@Test public void fail_delayed() { when(mockTransport.getAttributes()).thenReturn(Attributes.EMPTY); // Will call applyRequestMetadata(), which is no-op. DelayedStream stream = (DelayedStream) transport.newStream(method, origHeaders, callOptions); ArgumentCaptor<MetadataApplier> applierCaptor = ArgumentCaptor.forClass(null); verify(mockCreds).applyRequestMetadata( any(RequestInfo.class), same(mockExecutor), applierCaptor.capture()); Status error = Status.FAILED_PRECONDITION.withDescription("channel not secure for creds"); applierCaptor.getValue().fail(error); verify(mockTransport, never()).newStream(method, origHeaders, callOptions); FailingClientStream failingStream = (FailingClientStream) stream.getRealStream(); assertSame(error, failingStream.getError()); }
Example #24
Source Project: grpc-nebula-java Author: grpc-nebula File: RetriableStreamTest.java License: Apache License 2.0 | 6 votes |
@Test public void messageAvailable() { ClientStream mockStream1 = mock(ClientStream.class); doReturn(mockStream1).when(retriableStreamRecorder).newSubstream(0); retriableStream.start(masterListener); ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 = ArgumentCaptor.forClass(ClientStreamListener.class); verify(mockStream1).start(sublistenerCaptor1.capture()); ClientStreamListener listener = sublistenerCaptor1.getValue(); listener.headersRead(new Metadata()); MessageProducer messageProducer = mock(MessageProducer.class); listener.messagesAvailable(messageProducer); verify(masterListener).messagesAvailable(messageProducer); }
Example #25
Source Project: aws-glue-data-catalog-client-for-apache-hive-metastore Author: awslabs File: GlueMetastoreClientDelegateTest.java License: Apache License 2.0 | 6 votes |
@Test public void testGetPartitionByValuesWithCatalogId() throws Exception { List<String> values = Lists.newArrayList("foo", "bar"); Partition partition = new Partition().withDatabaseName(testDb.getName()) .withTableName(testTbl.getName()) .withValues(values) .withStorageDescriptor(TestObjects.getTestStorageDescriptor()); GetPartitionRequest request = new GetPartitionRequest() .withDatabaseName(testDb.getName()) .withTableName(testTbl.getName()) .withPartitionValues(values). withCatalogId(CATALOG_ID); when(glueClient.getPartition(request)).thenReturn(new GetPartitionResult().withPartition(partition)); org.apache.hadoop.hive.metastore.api.Partition result = metastoreClientDelegateCatalogId.getPartition(testDb.getName(), testTbl.getName(), values); ArgumentCaptor<GetPartitionRequest> captor = ArgumentCaptor.forClass(GetPartitionRequest.class); verify(glueClient, times(1)).getPartition(captor.capture()); assertThat(result.getValues(), is(values)); assertEquals(CATALOG_ID, captor.getValue().getCatalogId()); }
Example #26
Source Project: XS2A-Sandbox Author: adorsys File: AISControllerTest.java License: Apache License 2.0 | 6 votes |
@Test void aisDone() { // Given when(responseUtils.consentCookie(any())).thenReturn(COOKIE); when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(FINALISED, ConsentStatus.VALID)); when(responseUtils.redirect(anyString(), any())).thenReturn(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, FINALISED))); when(authService.resolveAuthConfirmationCodeRedirectUri(anyString(), anyString())).thenReturn(OK_URI); // When ResponseEntity<ConsentAuthorizeResponse> result = controller.aisDone(ENCRYPTED_ID, AUTH_ID, COOKIE, false, "code"); // Then assertEquals(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, FINALISED)), result); ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class); verify(responseUtils).redirect(urlCaptor.capture(), any()); assertEquals(OK_URI, urlCaptor.getValue()); }
Example #27
Source Project: XS2A-Sandbox Author: adorsys File: AISControllerTest.java License: Apache License 2.0 | 6 votes |
@Test void aisDone_nok() { // Given when(responseUtils.consentCookie(any())).thenReturn(COOKIE); when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(RECEIVED, ConsentStatus.REJECTED)); when(responseUtils.redirect(anyString(), any())).thenReturn(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, FINALISED))); when(authService.resolveAuthConfirmationCodeRedirectUri(anyString(), anyString())).thenReturn(""); // When ResponseEntity<ConsentAuthorizeResponse> result = controller.aisDone(ENCRYPTED_ID, AUTH_ID, COOKIE, false, "code"); // Then assertEquals(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, FINALISED)), result); ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class); verify(responseUtils).redirect(urlCaptor.capture(), any()); assertEquals(NOK_URI, urlCaptor.getValue()); }
Example #28
Source Project: sofa-jraft Author: sofastack File: AbstractClientServiceTest.java License: Apache License 2.0 | 6 votes |
@Test public void testCancel() throws Exception { ArgumentCaptor<InvokeCallback> callbackArg = ArgumentCaptor.forClass(InvokeCallback.class); PingRequest request = TestUtils.createPingRequest(); MockRpcResponseClosure<ErrorResponse> done = new MockRpcResponseClosure<>(); Future<Message> future = this.clientService.invokeWithDone(this.endpoint, request, done, -1); Mockito.verify(this.rpcClient).invokeAsync(eq(this.endpoint), eq(request), Mockito.any(), callbackArg.capture(), eq((long) this.rpcOptions.getRpcDefaultTimeout())); InvokeCallback cb = callbackArg.getValue(); assertNotNull(cb); assertNotNull(future); assertNull(done.getResponse()); assertNull(done.status); assertFalse(future.isDone()); future.cancel(true); ErrorResponse response = (ErrorResponse) this.rpcResponseFactory.newResponse(null, Status.OK()); cb.complete(response, null); // The closure should be notified with ECANCELED error code. done.latch.await(); assertNotNull(done.status); assertEquals(RaftError.ECANCELED.getNumber(), done.status.getCode()); }
Example #29
Source Project: spring-analysis-note Author: Vip-Augus File: StandardWebSocketClientTests.java License: MIT License | 5 votes |
@Test public void clientEndpointConfig() throws Exception { URI uri = new URI("ws://localhost/abc"); List<String> protocols = Collections.singletonList("abc"); this.headers.setSecWebSocketProtocol(protocols); this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class); verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class)); ClientEndpointConfig endpointConfig = captor.getValue(); assertEquals(protocols, endpointConfig.getPreferredSubprotocols()); }
Example #30
Source Project: plugins Author: open-osrs File: TimersPluginTest.java License: GNU General Public License v3.0 | 5 votes |
@Test public void testDmmHalfTb() { when(timersConfig.showTeleblock()).thenReturn(true); ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.SPAM, "", DMM_HALF_TELEBLOCK_MESSAGE, "", 0); timersPlugin.onChatMessage(chatMessage); ArgumentCaptor<InfoBox> captor = ArgumentCaptor.forClass(InfoBox.class); verify(infoBoxManager).addInfoBox(captor.capture()); TimerTimer infoBox = (TimerTimer) captor.getValue(); assertEquals(GameTimer.DMM_HALFTB, infoBox.getTimer()); }