Java Code Examples for org.mockito.ArgumentCaptor#forClass()

The following examples show how to use org.mockito.ArgumentCaptor#forClass() . 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: hop   File: ReplaceStringMetaTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetFields() throws HopTransformException {
  ReplaceStringMeta meta = new ReplaceStringMeta();
  meta.setFieldInStream( new String[] { FIELD_NAME } );
  meta.setFieldOutStream( new String[] { FIELD_NAME } );

  IValueMeta inputFieldMeta = mock( IValueMeta.class );
  when( inputFieldMeta.getStringEncoding() ).thenReturn( ENCODING_NAME );

  IRowMeta inputRowMeta = mock( IRowMeta.class );
  when( inputRowMeta.searchValueMeta( anyString() ) ).thenReturn( inputFieldMeta );

  TransformMeta nextTransform = mock( TransformMeta.class );
  IVariables variables = mock( IVariables.class );
  IHopMetadataProvider metadataProvider = mock( IHopMetadataProvider.class );
  meta.getFields( inputRowMeta, "test", null, nextTransform, variables, metadataProvider );

  ArgumentCaptor<IValueMeta> argument = ArgumentCaptor.forClass( IValueMeta.class );
  verify( inputRowMeta ).addValueMeta( argument.capture() );
  assertEquals( ENCODING_NAME, argument.getValue().getStringEncoding() );
}
 
Example 2
Source Project: sofa-jraft   File: SnapshotExecutorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDoSnapshotWithIntervalDist() throws Exception {
    final NodeOptions nodeOptions = new NodeOptions();
    nodeOptions.setSnapshotLogIndexMargin(5);
    Mockito.when(this.node.getOptions()).thenReturn(nodeOptions);
    Mockito.when(this.fSMCaller.getLastAppliedIndex()).thenReturn(6L);

    final ArgumentCaptor<SaveSnapshotClosure> saveSnapshotClosureArg = ArgumentCaptor
        .forClass(SaveSnapshotClosure.class);
    Mockito.when(this.fSMCaller.onSnapshotSave(saveSnapshotClosureArg.capture())).thenReturn(true);
    final SynchronizedClosure done = new SynchronizedClosure();
    this.executor.doSnapshot(done);
    final SaveSnapshotClosure closure = saveSnapshotClosureArg.getValue();
    assertNotNull(closure);
    closure.start(RaftOutter.SnapshotMeta.newBuilder().setLastIncludedIndex(6).setLastIncludedTerm(1).build());
    closure.run(Status.OK());
    done.await();
    this.executor.join();

    assertEquals(1, this.executor.getLastSnapshotTerm());
    assertEquals(6, this.executor.getLastSnapshotIndex());

}
 
Example 3
@Test
public void write_Flush() 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(3L); // fake some written bytes
  ConsumerRecord<Void, Record> record = record(schema1, "foo", 1, 10);
  underTest.write(record);

  verify(recordWriter).write(record.value());
  assertThat(underTest.getRecordCounter().get(), is(0L));
  verify(metrics).consumedBytes(10);
  verify(metrics).offsetHighwaterMark(0, 1);
  verify(metrics).uploadedBytes(3L);
  verify(metrics).uploadedEvents(1L);
  assertThat(writers.size(), is(0));
}
 
Example 4
@Test
public void testServerSideLoad() {
    final CommunityBranchPlugin testCase = new CommunityBranchPlugin();

    final CoreExtension.Context context = spy(mock(CoreExtension.Context.class, Mockito.RETURNS_DEEP_STUBS));
    when(context.getRuntime().getSonarQubeSide()).thenReturn(SonarQubeSide.SERVER);

    testCase.load(context);

    final ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
    verify(context, times(2)).addExtensions(argumentCaptor.capture(), argumentCaptor.capture());

    assertEquals(23, argumentCaptor.getAllValues().size());

    assertEquals(Arrays.asList(CommunityBranchFeatureExtension.class, CommunityBranchSupportDelegate.class),
                 argumentCaptor.getAllValues().subList(0, 2));
}
 
Example 5
Source Project: kafka-helmsman   File: TopicServiceImplTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testAlterConfiguration() {
  TopicService service = new TopicServiceImpl(adminClient, true);
  AlterConfigsResult result = mock(AlterConfigsResult.class);
  when(result.all()).thenReturn(KafkaFuture.completedFuture(null));
  when(adminClient.alterConfigs(any(Map.class), any(AlterConfigsOptions.class))).thenReturn(result);

  service.alterConfiguration(Collections.singletonList(
      new ConfiguredTopic("test", 3, (short) 2, Collections.singletonMap("k", "v"))));

  ArgumentCaptor<Map> alter = ArgumentCaptor.forClass(Map.class);
  ArgumentCaptor<AlterConfigsOptions> options = ArgumentCaptor.forClass(AlterConfigsOptions.class);
  verify(adminClient).alterConfigs((Map<ConfigResource, Config>) alter.capture(), options.capture());
  Assert.assertEquals(1, alter.getValue().size());
  ConfigResource expectedKey = new ConfigResource(TOPIC, "test");
  Assert.assertTrue(alter.getValue().containsKey(expectedKey));
  Assert.assertEquals("v", ((Config) alter.getValue().get(expectedKey)).get("k").value());
  Assert.assertTrue(options.getValue().shouldValidateOnly());
}
 
Example 6
Source Project: Moss   File: HipchatNotifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_onApplicationEvent_resolve() {
    @SuppressWarnings("unchecked")
    ArgumentCaptor<HttpEntity<Map<String, Object>>> httpRequest = ArgumentCaptor.forClass(
        (Class<HttpEntity<Map<String, Object>>>) (Class<?>) HttpEntity.class);

    when(restTemplate.postForEntity(isA(String.class), httpRequest.capture(), eq(Void.class))).thenReturn(
        ResponseEntity.ok().build());

    StepVerifier.create(notifier.notify(
        new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofDown())))
                .verifyComplete();
    StepVerifier.create(
        notifier.notify(new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofUp())))
                .verifyComplete();

    assertThat(httpRequest.getValue().getHeaders()).containsEntry("Content-Type",
        Collections.singletonList("application/json"));

    Map<String, Object> body = httpRequest.getValue().getBody();
    assertThat(body).containsEntry("color", "green");
    assertThat(body).containsEntry("message", "<strong>App</strong>/-id- is <strong>UP</strong>");
    assertThat(body).containsEntry("notify", Boolean.TRUE);
    assertThat(body).containsEntry("message_format", "html");

}
 
Example 7
@Test
@SneakyThrows
public void updateContact_shouldReturn204_whenInputIsValidAndContactExists() {

    when(service.findContact(anyLong())).thenReturn(Optional.of(contactPersisted()));

    mockMvc.perform(put("/contacts/{id}", 1L)
            .contentType(MediaType.APPLICATION_JSON)
            .content(fromFile("json/contact/put-with-valid-payload.json")))
            .andDo(print())
            .andExpect(status().isNoContent());

    verify(mapper).update(any(Contact.class), any(ContactResourceInput.class));

    ArgumentCaptor<Contact> contactArgumentCaptor = ArgumentCaptor.forClass(Contact.class);
    verify(service).findContact(anyLong());
    verify(service).updateContact(contactArgumentCaptor.capture());
    verifyNoMoreInteractions(service);

    verifyZeroInteractions(patchHelper);

    assertThat(contactArgumentCaptor.getValue()).isEqualToComparingFieldByFieldRecursively(contactToUpdate());
}
 
Example 8
@Test
@DisabledOnOs(WINDOWS)
public void testExtractImageReturningSquashedImage() throws ExecutableRunnerException {

    final String image = "ubuntu:latest";
    final String imageId = null;
    final String tar = null;
    final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class);

    final Extraction extraction = extract(image, imageId, tar, fakeContainerFileSystemFile, fakeSquashedImageFile, executableRunner);

    assertEquals("ubuntu:latest", extraction.getMetaData(DockerExtractor.DOCKER_IMAGE_NAME_META_DATA).get());
    // When Detect gets both .tar.gz files back, should prefer the squashed image
    assertTrue(extraction.getMetaData(DockerExtractor.DOCKER_TAR_META_DATA).get().getName().endsWith("_squashedimage.tar.gz"));

    final ArgumentCaptor<Executable> executableArgumentCaptor = ArgumentCaptor.forClass(Executable.class);
    Mockito.verify(executableRunner).execute(executableArgumentCaptor.capture());
    final Executable executableToVerify = executableArgumentCaptor.getValue();
    final List<String> command = executableToVerify.getCommand();
    assertTrue(command.get(0).endsWith("/fake/test/java"));
    assertEquals("-jar", command.get(1));
    assertTrue(command.get(2).endsWith("/fake/test/dockerinspector.jar"));
    assertTrue(command.get(3).startsWith("--spring.config.location="));
    assertTrue(command.get(3).endsWith("/application.properties"));
    assertEquals("--docker.image=ubuntu:latest", command.get(4));
}
 
Example 9
private PubSubMessage assertPubSubMessage(Transaction expectedTransaction, int numSendTries) throws Exception {
    ArgumentCaptor<Message<PubSubMessage>> argument = ArgumentCaptor.forClass(Message.class);
    verify(messageChannel, times(numSendTries)).send(argument.capture());
    var actual = argument.getValue().getPayload();
    assertThat(actual.getConsensusTimestamp()).isEqualTo(CONSENSUS_TIMESTAMP);
    assertThat(actual.getTransaction()).isEqualTo(expectedTransaction.toBuilder()
            .clearBodyBytes()
            .setBody(TransactionBody.parseFrom(expectedTransaction.getBodyBytes()))
            .build());
    assertThat(actual.getTransactionRecord()).isEqualTo(DEFAULT_RECORD);
    assertThat(argument.getValue().getHeaders()).describedAs("Headers contain consensus timestamp")
            .hasSize(3) // +2 are default attributes 'id' and 'timestamp' (publish)
            .containsEntry("consensusTimestamp", CONSENSUS_TIMESTAMP);
    return actual;
}
 
Example 10
Source Project: besu   File: BesuCommandTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void requiredBlocksEmptyWhenNotSpecified() {
  parseCommand();

  @SuppressWarnings("unchecked")
  final ArgumentCaptor<Map<Long, Hash>> requiredBlocksArg = ArgumentCaptor.forClass(Map.class);

  verify(mockControllerBuilder).requiredBlocks(requiredBlocksArg.capture());
  verify(mockControllerBuilder).build();

  assertThat(commandOutput.toString()).isEmpty();
  assertThat(commandErrorOutput.toString()).isEmpty();

  assertThat(requiredBlocksArg.getValue()).isEmpty();
}
 
Example 11
@Test
public void test_poll_shared_publishes() throws NoMessageIdAvailableException {
    final OrderedTopicHandler orderedTopicHandler = mock(OrderedTopicHandler.class);
    final byte flags = SubscriptionFlags.getDefaultFlags(true, false, false);
    when(sharedSubscriptionService.getSharedSubscriber(anyString())).thenReturn(ImmutableSet.of(
            new SubscriberWithQoS("client1", 2, flags, 1),
            new SubscriberWithQoS("client2", 2, flags, 2)));
    when(channelPersistence.get("client1")).thenReturn(channel);
    when(channelPersistence.get("client2")).thenReturn(null);

    when(clientQueuePersistence.readShared(eq("group/topic"), anyInt(), anyLong())).thenReturn(Futures.immediateFuture(
            ImmutableList.of(createPublish(1), createPublish(1), TestMessageUtil.createMqtt3Publish(QoS.AT_MOST_ONCE))));

    when(messageIDPool.takeNextId()).thenReturn(2).thenReturn(3);
    when(channel.isActive()).thenReturn(true);
    final AtomicInteger inFlightCount = new AtomicInteger(0);
    when(channel.attr(ChannelAttributes.IN_FLIGHT_MESSAGES)).thenReturn(new TestChannelAttribute<>(inFlightCount));
    when(channel.attr(ChannelAttributes.IN_FLIGHT_MESSAGES_SENT)).thenReturn(new TestChannelAttribute<>(true));

    when(pipeline.get(OrderedTopicHandler.class)).thenReturn(orderedTopicHandler);
    when(orderedTopicHandler.unacknowledgedMessages()).thenReturn(new HashSet<>());


    publishPollService.pollSharedPublishes("group/topic");

    final ArgumentCaptor<PUBLISH> captor = ArgumentCaptor.forClass(PUBLISH.class);
    verify(pipeline, times(3)).fireUserEventTriggered(captor.capture());
    verify(messageIDPool, times(2)).takeNextId();

    final List<PUBLISH> values = captor.getAllValues();
    assertEquals(2, values.get(0).getPacketIdentifier());
    assertEquals(QoS.AT_LEAST_ONCE, values.get(0).getQoS());
    assertEquals(1, values.get(0).getSubscriptionIdentifiers().get(0));

    assertEquals(3, values.get(1).getPacketIdentifier());
    assertEquals(QoS.AT_LEAST_ONCE, values.get(1).getQoS());
    assertEquals(1, values.get(1).getSubscriptionIdentifiers().get(0));
    assertEquals(3, inFlightCount.get());
}
 
Example 12
private void verifyCallListenerClosed(
    ClientCall.Listener<Integer> listener, Status.Code code, Throwable cause) {
  ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(null);
  verify(listener).onClose(captor.capture(), any(Metadata.class));
  Status rpcStatus = captor.getValue();
  assertEquals(code, rpcStatus.getCode());
  assertSame(cause, rpcStatus.getCause());
  verifyNoMoreInteractions(listener);
}
 
Example 13
@Test
public void onTimeoutAfterHandlerInitialized() throws Exception  {
	this.emitter.initialize(this.handler);

	ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
	verify(this.handler).onTimeout(captor.capture());
	verify(this.handler).onCompletion(any());

	Runnable runnable = mock(Runnable.class);
	this.emitter.onTimeout(runnable);

	assertNotNull(captor.getValue());
	captor.getValue().run();
	verify(runnable).run();
}
 
Example 14
@Test
@DisabledOnOs(WINDOWS)
public void testExtractTarReturningOriginalTar() throws ExecutableRunnerException {

    final String image = null;
    final String imageId = null;
    final String tar = fakeDockerTarFile.getAbsolutePath();
    final ExecutableRunner executableRunner = Mockito.mock(ExecutableRunner.class);

    final Extraction extraction = extract(image, imageId, tar, null, null, executableRunner);

    // No returned .tar.gz: scan given docker tar instead
    assertTrue(extraction.getMetaData(DockerExtractor.DOCKER_IMAGE_NAME_META_DATA).get().endsWith("testDockerTarfile.tar"));
    assertTrue(extraction.getMetaData(DockerExtractor.DOCKER_TAR_META_DATA).get().getName().endsWith("testDockerTarfile.tar"));

    final ArgumentCaptor<Executable> executableArgumentCaptor = ArgumentCaptor.forClass(Executable.class);
    Mockito.verify(executableRunner).execute(executableArgumentCaptor.capture());
    final Executable executableToVerify = executableArgumentCaptor.getValue();
    final List<String> command = executableToVerify.getCommand();
    assertTrue(command.get(0).endsWith("/fake/test/java"));
    assertEquals("-jar", command.get(1));
    assertTrue(command.get(2).endsWith("/fake/test/dockerinspector.jar"));
    assertTrue(command.get(3).startsWith("--spring.config.location="));
    assertTrue(command.get(3).endsWith("/application.properties"));
    assertTrue(command.get(4).startsWith("--docker.tar="));
    assertTrue(command.get(4).endsWith("testDockerTarfile.tar"));
}
 
Example 15
@Test
public void testSyncDataFromOMFullSnapshot() throws Exception {

  // Empty OM DB to start with.
  ReconOMMetadataManager omMetadataManager = getTestReconOmMetadataManager(
      initializeEmptyOmMetadataManager(temporaryFolder.newFolder()),
      temporaryFolder.newFolder());
  ReconTaskStatusDao reconTaskStatusDaoMock =
      mock(ReconTaskStatusDao.class);
  doNothing().when(reconTaskStatusDaoMock)
      .update(any(ReconTaskStatus.class));

  ReconTaskController reconTaskControllerMock = getMockTaskController();
  when(reconTaskControllerMock.getReconTaskStatusDao())
      .thenReturn(reconTaskStatusDaoMock);
  doNothing().when(reconTaskControllerMock)
      .reInitializeTasks(omMetadataManager);

  OzoneManagerServiceProviderImpl ozoneManagerServiceProvider =
      new MockOzoneServiceProvider(configuration, omMetadataManager,
          reconTaskControllerMock, new ReconUtils(), ozoneManagerProtocol);

  OzoneManagerSyncMetrics metrics = ozoneManagerServiceProvider.getMetrics();
  assertEquals(0, metrics.getNumSnapshotRequests().value());

  // Should trigger full snapshot request.
  ozoneManagerServiceProvider.syncDataFromOM();

  ArgumentCaptor<ReconTaskStatus> captor =
      ArgumentCaptor.forClass(ReconTaskStatus.class);
  verify(reconTaskStatusDaoMock, times(1))
      .update(captor.capture());
  assertTrue(captor.getValue().getTaskName()
      .equals(OmSnapshotRequest.name()));
  verify(reconTaskControllerMock, times(1))
      .reInitializeTasks(omMetadataManager);
  assertEquals(1, metrics.getNumSnapshotRequests().value());
}
 
Example 16
private ArgumentCaptor<TransactionValidationParams> transactionValidationParamCaptor() {
  final ArgumentCaptor<TransactionValidationParams> txValidationParamCaptor =
      ArgumentCaptor.forClass(TransactionValidationParams.class);
  when(transactionValidator.validate(any())).thenReturn(ValidationResult.valid());
  // returning invalid transaction to halt method execution
  when(transactionValidator.validateForSender(any(), any(), txValidationParamCaptor.capture()))
      .thenReturn(
          ValidationResult.invalid(
              TransactionValidator.TransactionInvalidReason.INCORRECT_NONCE));
  return txValidationParamCaptor;
}
 
Example 17
Source Project: arcusplatform   File: EmailProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSendEmailWithPartialName() throws DispatchException, DispatchUnsupportedByUserException, JsonParseException, JsonMappingException, IOException {
   Mockito.when(person.getFirstName()).thenReturn("");
   ArgumentCaptor<Request> mailRequestCaptor = ArgumentCaptor.forClass(Request.class);
   uut.notifyCustomer(notification);
   Mockito.verify(sendGrid).api(mailRequestCaptor.capture());

   validateEmail(mailRequestCaptor.getValue(), expectedEmailFromEmail, expectedEmailFromEmail, expectedEmailBody);
}
 
Example 18
@Test
public void broadcastRegistry() throws Exception {

	TestSimpUser simpUser1 = new TestSimpUser("joe");
	TestSimpUser simpUser2 = new TestSimpUser("jane");

	simpUser1.addSessions(new TestSimpSession("123"));
	simpUser1.addSessions(new TestSimpSession("456"));

	HashSet<SimpUser> simpUsers = new HashSet<>(Arrays.asList(simpUser1, simpUser2));
	given(this.localRegistry.getUsers()).willReturn(simpUsers);

	getUserRegistryTask().run();

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(this.brokerChannel).send(captor.capture());

	Message<?> message = captor.getValue();
	assertNotNull(message);
	MessageHeaders headers = message.getHeaders();
	assertEquals("/topic/simp-user-registry", SimpMessageHeaderAccessor.getDestination(headers));

	MultiServerUserRegistry remoteRegistry = new MultiServerUserRegistry(mock(SimpUserRegistry.class));
	remoteRegistry.addRemoteRegistryDto(message, this.converter, 20000);
	assertEquals(2, remoteRegistry.getUserCount());
	assertNotNull(remoteRegistry.getUser("joe"));
	assertNotNull(remoteRegistry.getUser("jane"));
}
 
Example 19
@Test
public void writeInactivity() throws Exception {
	this.messageHandler.setHeartbeatValue(new long[] {1, 0});
	this.messageHandler.setTaskScheduler(this.taskScheduler);
	this.messageHandler.start();

	ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
	verify(this.taskScheduler).scheduleWithFixedDelay(taskCaptor.capture(), eq(1L));
	Runnable heartbeatTask = taskCaptor.getValue();
	assertNotNull(heartbeatTask);

	String id = "sess1";
	TestPrincipal user = new TestPrincipal("joe");
	Message<String> connectMessage = createConnectMessage(id, user, new long[] {0, 1});
	this.messageHandler.handleMessage(connectMessage);

	Thread.sleep(10);
	heartbeatTask.run();

	verify(this.clientOutChannel, times(2)).send(this.messageCaptor.capture());
	List<Message<?>> messages = this.messageCaptor.getAllValues();
	assertEquals(2, messages.size());

	MessageHeaders headers = messages.get(0).getHeaders();
	assertEquals(SimpMessageType.CONNECT_ACK, headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER));
	headers = messages.get(1).getHeaders();
	assertEquals(SimpMessageType.HEARTBEAT, headers.get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER));
	assertEquals(id, headers.get(SimpMessageHeaderAccessor.SESSION_ID_HEADER));
	assertEquals(user, headers.get(SimpMessageHeaderAccessor.USER_HEADER));
}
 
Example 20
@Test
public void pingSentThenIdleThenActiveThenAck() {
  keepAliveManager.onTransportActive();
  ArgumentCaptor<Runnable> sendPingCaptor = ArgumentCaptor.forClass(Runnable.class);
  verify(scheduler, times(1))
      .schedule(sendPingCaptor.capture(), isA(Long.class), isA(TimeUnit.class));
  Runnable sendPing = sendPingCaptor.getValue();
  ScheduledFuture<?> shutdownFuture = mock(ScheduledFuture.class);
  // ping scheduled
  doReturn(shutdownFuture)
      .when(scheduler).schedule(isA(Runnable.class), isA(Long.class), isA(TimeUnit.class));

  // Mannually running the Runnable will send the ping.
  ticker.time = 1000;
  sendPing.run();

  // shutdown scheduled
  verify(scheduler, times(2))
      .schedule(sendPingCaptor.capture(), isA(Long.class), isA(TimeUnit.class));
  verify(keepAlivePinger).ping();

  keepAliveManager.onTransportIdle();

  keepAliveManager.onTransportActive();

  keepAliveManager.onDataReceived();

  // another ping scheduled
  verify(scheduler, times(3))
      .schedule(sendPingCaptor.capture(), isA(Long.class), isA(TimeUnit.class));
}