Java Code Examples for org.mockito.ArgumentCaptor

The following are top voted examples for showing how to use org.mockito.ArgumentCaptor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: monarch   File: RegisterInterest61Test.java   Source Code and License 8 votes vote down vote up
@Test
public void oldSecurityShouldFailIfNotAuthorized() throws Exception {
  when(this.securityService.isClientSecurityRequired()).thenReturn(true);
  when(this.securityService.isIntegratedSecurity()).thenReturn(false);

  doThrow(new NotAuthorizedException("")).when(this.authzRequest)
      .registerInterestAuthorize(eq(REGION_NAME), eq(KEY), anyInt(), any());

  this.registerInterest61.cmdExecute(this.message, this.serverConnection, 0);

  verify(this.authzRequest).registerInterestAuthorize(eq(REGION_NAME), eq(KEY), anyInt(), any());

  ArgumentCaptor<NotAuthorizedException> argument =
      ArgumentCaptor.forClass(NotAuthorizedException.class);
  verify(this.chunkedResponseMessage).addObjPart(argument.capture());

  assertThat(argument.getValue()).isExactlyInstanceOf(NotAuthorizedException.class);
  verify(this.chunkedResponseMessage).sendChunk(this.serverConnection);
}
 
Example 2
Project: mux2fs   File: MirrorFsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testReleaseClosesOpenFileChannel()
		throws Exception {
	// Given
	FileHandleFiller filler = mock(FileHandleFiller.class);
	ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class);
	doNothing().when(filler).setFileHandle(handleCaptor.capture());
	Path fooBar = mockPath(mirrorRoot, "foo.bar");
	FileChannel fileChannel = mock(FileChannel.class);
	when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(fileChannel);
	fs.open("foo.bar", filler);
	// When
	int result = fs.release("foo.bar", handleCaptor.getValue());
	// Then
	assertThat(result).isEqualTo(SUCCESS);
	verify(fileChannelCloser).close(fileChannel);
	verifyNoMoreInteractions(fileChannel);
}
 
Example 3
Project: verify-hub   File: Cycle3MatchRequestSentStateControllerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void statusShouldSendNoMatchResponseToTransaction_whenNoMatchResponseSentFromMatchingServiceCycle3Match() throws Exception {
    final String requestId = "requestId";
    final SessionId sessionId = SessionId.createNewSessionId();
    Cycle3MatchRequestSentState state = aCycle3MatchRequestSentState().withSessionId(sessionId).withRequestId(requestId).build();
    Cycle3MatchRequestSentStateController controller =
            new Cycle3MatchRequestSentStateController(state, eventSinkHubEventLogger, stateTransitionAction, policyConfiguration,
                    null, null, transactionsConfigProxy, matchingServiceConfigProxy, assertionRestrictionFactory, attributeQueryService);
    ArgumentCaptor<NoMatchState> argumentCaptor = ArgumentCaptor.forClass(NoMatchState.class);
    NoMatchFromMatchingService noMatchFromMatchingService = new NoMatchFromMatchingService(matchingServiceEntityId, requestId);

    controller.handleNoMatchResponseFromMatchingService(noMatchFromMatchingService);

    verify(stateTransitionAction, times(1)).transitionTo(argumentCaptor.capture());
    NoMatchStateController noMatchStateController = new NoMatchStateController(argumentCaptor.getValue(), responseFromHubFactory);
    ResponseProcessingDetails responseProcessingDetails = noMatchStateController.getResponseProcessingDetails();
    assertThat(responseProcessingDetails.getResponseProcessingStatus()).isEqualTo(ResponseProcessingStatus.SEND_NO_MATCH_RESPONSE_TO_TRANSACTION);
    assertThat(responseProcessingDetails.getSessionId()).isEqualTo(sessionId);
}
 
Example 4
Project: q-mail   File: MessageCryptoHelperTest.java   Source Code and License 6 votes vote down vote up
private void processSMimeEncryptedMessageAndCaptureMocks(
        Message message, Body encryptedBody, OutputStream outputStream)
        throws Exception {
    messageCryptoHelper.asyncStartOrResumeProcessingMessage(message, messageCryptoCallback,
            null, null, false);

    ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
    ArgumentCaptor<SMimeDataSource> dataSourceCaptor = ArgumentCaptor.forClass(SMimeDataSource.class);
    ArgumentCaptor<ISMimeSinkResultCallback> callbackCaptor = ArgumentCaptor.forClass(
            ISMimeSinkResultCallback.class);
    verify(sMimeApi).executeApiAsync(intentCaptor.capture(), dataSourceCaptor.capture(),
            any(SMimeDataSink.class), callbackCaptor.capture());

    capturedApiIntent = intentCaptor.getValue();
    capturedSMimeCallback = callbackCaptor.getValue();

    SMimeDataSource dataSource = dataSourceCaptor.getValue();
    dataSource.writeTo(outputStream);
    verify(encryptedBody).writeTo(outputStream);
}
 
Example 5
Project: verify-hub   File: EventSinkHubEventLoggerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void logEventSinkHubEvent_shouldSendEvent() throws Exception {
    EventSinkHubEventLogger eventLogger = new EventSinkHubEventLogger(serviceInfo, eventSinkProxy);
    ArgumentCaptor<EventSinkHubEvent> eventCaptor = ArgumentCaptor.forClass(EventSinkHubEvent.class);
    SessionId expectedSessionId = aSessionId().build();

    eventLogger.logRequestFromHub(expectedSessionId, "transaction-entity-id");
    verify(eventSinkProxy).logHubEvent(eventCaptor.capture());

    EventSinkHubEvent actualEvent = eventCaptor.getValue();

    assertThat(actualEvent.getEventType()).isEqualTo(HUB_EVENT);
    assertThat(actualEvent.getSessionId()).isEqualTo(expectedSessionId.getSessionId());
    Map<EventDetailsKey, String> details = actualEvent.getDetails();

    assertThat(details.containsKey(hub_event_type)).isTrue();
    String hubEventType = details.get(hub_event_type);
    assertThat(hubEventType).isEqualTo(RECEIVED_AUTHN_REQUEST_FROM_HUB);
}
 
Example 6
Project: smartlog   File: SmartLogTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testResultWithLevelAndThrowableAndArgs() throws Exception {
    SmartLog.start(output);

    SmartLog.format(new SimpleTextFormat("${result}"));
    final RuntimeException exception = new RuntimeException("test");
    SmartLog.result(LogLevel.WARN, exception, "test-result: %d", 42);

    SmartLog.finish();

    final ArgumentCaptor<String> msgCaptor = ArgumentCaptor.forClass(String.class);
    final ArgumentCaptor<Exception> exceptionCaptor = ArgumentCaptor.forClass(Exception.class);
    Mockito.verify(logger).warn(msgCaptor.capture(), exceptionCaptor.capture());

    Assertions.assertThat(msgCaptor.getValue())
            .matches("test-result: 42");
    assertThat(exceptionCaptor.getValue())
            .isSameAs(exception);
}
 
Example 7
Project: Phial   File: OverlayViewTest.java   Source Code and License 6 votes vote down vote up
@Test
public void show_and_remove_button_several_activities() {
    final ArgumentCaptor<View> viewArgumentCaptor = ArgumentCaptor.forClass(View.class);

    final WindowManager windowManager1 = mock(WindowManager.class);
    final Activity activity1 = mockActivity(windowManager1);
    final ArgumentCaptor<View> viewArgumentCaptor1 = ArgumentCaptor.forClass(View.class);

    view.showButton(activity, false);
    verify(windowManager).addView(viewArgumentCaptor.capture(), any());

    view.showButton(activity1, false);
    verify(windowManager1).addView(viewArgumentCaptor1.capture(), any());

    view.removeButton(activity);
    verify(windowManager).removeView(viewArgumentCaptor.getValue());

    view.removeButton(activity1);
    verify(windowManager1).removeView(viewArgumentCaptor1.getValue());
}
 
Example 8
Project: bluetooth-manager-tinyb   File: TinyBAdapterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testEnablePoweredNotifications() throws Exception {
    Notification<Boolean> notification = mock(Notification.class);
    ArgumentCaptor<BluetoothNotification> captor = ArgumentCaptor.forClass(BluetoothNotification.class);
    doNothing().when(bluetoothAdapter).enablePoweredNotifications(captor.capture());

    tinyBAdapter.enablePoweredNotifications(notification);

    verify(bluetoothAdapter, times(1)).enablePoweredNotifications(captor.getValue());
    verifyNoMoreInteractions(bluetoothAdapter, notification);

    captor.getValue().run(Boolean.TRUE);
    verify(notification, times(1)).notify(Boolean.TRUE);

    doThrow(RuntimeException.class).when(notification).notify(anyBoolean());
    captor.getValue().run(Boolean.FALSE);
    verify(notification, times(1)).notify(Boolean.FALSE);
}
 
Example 9
Project: oscm-app   File: APPAuthenticationServiceBeanIT.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testAuthenticateTMForController_noControllerSettings()
        throws Throwable {

    // given
    VOUserDetails manager = createVOUserDetails(10000, "user", "tp123");
    Mockito.doThrow(new ConfigurationException("test")).when(configService)
            .getAuthenticationForBESTechnologyManager(anyString(),
                    any(ServiceInstance.class), Matchers.anyMap());
    Mockito.doReturn(null).when(authService)
            .getAuthenticatedTMForController(anyString(),
                    any(PasswordAuthentication.class));
    ArgumentCaptor<PasswordAuthentication> ac = ArgumentCaptor
            .forClass(PasswordAuthentication.class);

    // when
    authenticateTMForController(CTRL_ID, manager.getUserId(), "pass");

    // then
    verify(authService).getAuthenticatedTMForController(
            anyString(), ac.capture());
    assertEquals(manager.getUserId(), ac.getValue().getUserName());
    assertEquals("pass", ac.getValue().getPassword());
}
 
Example 10
Project: oscm   File: PricingServiceBeanTest.java   Source Code and License 6 votes vote down vote up
@Test
public void saveOperatorRevenueShare() throws Exception {
    PORevenueShare po = new PORevenueShare();
    po.setKey(101L);
    po.setRevenueShare(BigDecimal.TEN);
    po.setVersion(2);
    ArgumentCaptor<RevenueShareModel> captor = ArgumentCaptor
            .forClass(RevenueShareModel.class);

    // when
    Response response = bean.saveOperatorRevenueShare(1L, po);

    // then
    assertTrue(response.getResults().isEmpty());
    assertTrue(response.getWarnings().isEmpty());
    assertTrue(response.getReturnCodes().isEmpty());
    verify(bean.spPartnerServiceLocal, times(1)).saveOperatorRevenueShare(
            eq(1L), captor.capture(), eq(2));
    assertEquals(BigDecimal.TEN, captor.getValue().getRevenueShare());
    assertEquals(RevenueShareModelType.OPERATOR_REVENUE_SHARE, captor
            .getValue().getRevenueShareModelType());
    assertEquals(101L, captor.getValue().getKey());
}
 
Example 11
Project: crnk-framework   File: RepositoryFilterTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void findOne() throws Exception {

	resourceAdapter.findOne(1L, queryAdapter);

	ArgumentCaptor<Iterable> linksResources = ArgumentCaptor.forClass(Iterable.class);
	ArgumentCaptor<Iterable> metaResources = ArgumentCaptor.forClass(Iterable.class);
	ArgumentCaptor<RepositoryFilterContext> contexts = ArgumentCaptor.forClass(RepositoryFilterContext.class);

	Mockito.verify(filter, Mockito.times(1)).filterRequest(contexts.capture(), Mockito.any(RepositoryRequestFilterChain.class));
	Mockito.verify(filter, Mockito.times(1)).filterResult(Mockito.any(RepositoryFilterContext.class), Mockito.any(RepositoryResultFilterChain.class));
	Mockito.verify(filter, Mockito.times(1)).filterLinks(Mockito.any(RepositoryFilterContext.class), linksResources.capture(), Mockito.any(RepositoryLinksFilterChain.class));
	Mockito.verify(filter, Mockito.times(1)).filterMeta(Mockito.any(RepositoryFilterContext.class), metaResources.capture(), Mockito.any(RepositoryMetaFilterChain.class));

	Assert.assertEquals(1, linksResources.getAllValues().size());
	Assert.assertEquals(1, metaResources.getAllValues().size());
	Assert.assertEquals(1, contexts.getAllValues().size());
	RepositoryFilterContext context = contexts.getAllValues().iterator().next();
	RepositoryRequestSpec requestSpec = context.getRequest();
	Assert.assertEquals(queryAdapter, requestSpec.getQueryAdapter());
	Assert.assertEquals(1L, requestSpec.getId());
	Assert.assertEquals(Collections.singleton(1L), requestSpec.getIds());
	Assert.assertSame(querySpec, requestSpec.getQuerySpec(userInfo));
}
 
Example 12
Project: hashsdn-controller   File: Bug4513Test.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testDataChangeListener() throws Exception {
    DataChangeListener listener = mock(DataChangeListener.class);
    InstanceIdentifier<ListItem> wildCard = InstanceIdentifier.builder(ListenerTest.class)
            .child(ListItem.class).build();
    ListenerRegistration<DataChangeListener> reg = getDataBroker().registerDataChangeListener(
            LogicalDatastoreType.OPERATIONAL, wildCard, listener, AsyncDataBroker.DataChangeScope.SUBTREE);

    final ListItem item = writeListItem();

    ArgumentCaptor<AsyncDataChangeEvent> captor = ArgumentCaptor.forClass(AsyncDataChangeEvent.class);

    verify(listener, timeout(100)).onDataChanged(captor.capture());

    AsyncDataChangeEvent event = captor.getValue();
    assertEquals("createdData", 1, event.getCreatedData().size());
    assertEquals("ListItem", item, event.getCreatedData().values().iterator().next());
}
 
Example 13
Project: waggle-dance   File: MonitoredAspectTest.java   Source Code and License 6 votes vote down vote up
@Test
public void monitorFailuresForSpecificMetastore() throws Throwable {
  CurrentMonitoredMetaStoreHolder.monitorMetastore("metastoreName");
  when(pjp.proceed()).thenThrow(new ClassCastException());
  try {
    aspect.monitor(pjp, monitored);
  } catch (ClassCastException e) {
    // Expected
  }

  ArgumentCaptor<String> metricCaptor = ArgumentCaptor.forClass(String.class);
  verify(counterService, times(2)).increment(metricCaptor.capture());
  assertThat(metricCaptor.getAllValues().get(0), is("counter.Type_Anonymous.myMethod.metastoreName.calls"));
  assertThat(metricCaptor.getAllValues().get(1), is("counter.Type_Anonymous.myMethod.metastoreName.failure"));

  metricCaptor = ArgumentCaptor.forClass(String.class);
  ArgumentCaptor<Long> durationCaptor = ArgumentCaptor.forClass(Long.class);
  verify(gaugeService).submit(metricCaptor.capture(), durationCaptor.capture());
  assertThat(metricCaptor.getValue(), is("timer.Type_Anonymous.myMethod.metastoreName.duration"));
}
 
Example 14
Project: NioSmtpClient   File: SmtpSessionTest.java   Source Code and License 6 votes vote down vote up
@Test
public void itCanAuthenticateWithAuthLogin() throws Exception {
  String username = "user";
  String password = "password";

  // do the initial request, which just includes the username
  session.authLogin("user", "password");

  verify(channel).writeAndFlush(new DefaultSmtpRequest("AUTH", "LOGIN", encodeBase64(username)));

  // now the second request, which sends the password
  responseFuture.complete(Lists.newArrayList(INTERMEDIATE_RESPONSE));

  // this is sent to the second invocation of writeAndFlush
  ArgumentCaptor<Object> bufCaptor = ArgumentCaptor.forClass(Object.class);
  verify(channel, times(2)).writeAndFlush(bufCaptor.capture());
  ByteBuf capturedBuffer = (ByteBuf) bufCaptor.getAllValues().get(1);

  String actualString = capturedBuffer.toString(0, capturedBuffer.readableBytes(), StandardCharsets.UTF_8);
  assertThat(actualString).isEqualTo(encodeBase64(password) + "\r\n");
}
 
Example 15
Project: GitHub   File: LoggingInterceptorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testLogEmptyList() throws Exception {

    final TiLog.Logger logger = mock(TiLog.Logger.class);
    final LoggingInterceptor loggingInterceptor = new LoggingInterceptor(logger);
    final TestView view = loggingInterceptor.intercept(new TestViewImpl());

    final ArgumentCaptor<String> msgCaptor = ArgumentCaptor.forClass(String.class);

    view.twoArgs(new ArrayList(), "B");
    verify(logger).log(anyInt(), anyString(), msgCaptor.capture());

    assertThat(msgCaptor.getValue())
            .matches("twoArgs\\("
                    + "\\{ArrayList\\[0\\]@[\\da-f]{1,8}\\} \\[\\], "
                    + "B"
                    + "\\)");
}
 
Example 16
Project: asaf-project   File: StateBuilder.java   Source Code and License 6 votes vote down vote up
StateBuilder getFruitSuccess(final FruitPojo fruitPojo) {

        List<FruitPojo> fruitList = new ArrayList<>();
        fruitList.add(fruitPojo);

        final ArgumentCaptor<SuccessCallbackWithPayload> callback = ArgumentCaptor.forClass(SuccessCallbackWithPayload.class);

        doAnswer(__ -> {
            callback.getValue().success(fruitList);
            return null;
        })

                .when(mockCallProcessor)
                .processCall(any(), any(), any(), callback.capture(), any());

        return this;
    }
 
Example 17
Project: oscm   File: UpdateUserCtrlTest.java   Source Code and License 6 votes vote down vote up
@Test
public void save() throws Exception {
    doReturn(user.getUserId()).when(ctrl).getSelectedUserId();
    doReturn(Boolean.FALSE).when(ctrl).isCurrentUserRolesChanged();
    ctrl.init(uas);
    updateData(model);

    String outcome = ctrl.save();

    assertEquals(BaseBean.OUTCOME_SUCCESS, outcome);
    verify(ctrl.getUi()).handle(response, BaseBean.INFO_USER_SAVED,
            model.getUserId().getValue());
    ArgumentCaptor<POUserAndSubscriptions> ac = ArgumentCaptor
            .forClass(POUserAndSubscriptions.class);
    verify(us).saveUserAndSubscriptionAssignment(ac.capture(),
            anyListOf(POUserGroup.class));
    verifyDataUpdate(ac.getValue());
}
 
Example 18
Project: oscm   File: IdentityServiceBeanMailSendingTest.java   Source Code and License 6 votes vote down vote up
@Test
public void sendMailToCreatedUser_ManagerRole_SAML_SP() throws Exception {
    // given a SAML_SP authentication mode and a user with manager role
    doReturn(Boolean.TRUE).when(cs).isServiceProvider();

    addRole(pUser, UserRoleType.SERVICE_MANAGER);

    // when sending a mail to the created user
    idSrv.sendMailToCreatedUser("secret", true, new Marketplace(), pUser);

    // then verify that mail parameters are correct
    verify(idSrv.cm, times(1)).getBaseUrlWithTenant(anyString());
    verify(idSrv.cm, times(0)).getMarketplaceUrl(anyString());

    ArgumentCaptor<Object[]> ac = ArgumentCaptor.forClass(Object[].class);
    verify(cm, times(1)).sendMail(eq(pUser),
            eq(EmailType.USER_CREATED_SAML_SP), ac.capture(),
            any(Marketplace.class));
    Object[] value = ac.getValue();
    assertEquals(pUser.getUserId(), value[0]);
}
 
Example 19
Project: oscm   File: UpdateMarketplaceBeanTest.java   Source Code and License 6 votes vote down vote up
@Test
public void updateMarketplace_OrgNotChanged() throws Exception {
    ArgumentCaptor<VOMarketplace> captor = ArgumentCaptor
            .forClass(VOMarketplace.class);

    Marketplace model = umpb.getModel();
    String mId = "marketplaceId";
    model.setMarketplaceId(mId);
    model.setOwningOrganizationId("owningOrganizationId");
    model.setOriginalOrgId(model.getOwningOrganizationId());

    umpb.updateMarketplace();

    verify(mmps, times(1)).updateMarketplace(captor.capture(),
            any(POMarketplacePriceModel.class),
            any(POPartnerPriceModel.class));
    VOMarketplace value = captor.getValue();
    verifyValueObject(model, value);

    verify(umpb, times(1)).addMessage(anyString(),
            eq(FacesMessage.SEVERITY_INFO),
            eq(BaseBean.INFO_MARKETPLACE_SAVED), eq(new Object[] { mId }));
}
 
Example 20
Project: trading4j   File: ExceptionHandlerTest.java   Source Code and License 6 votes vote down vote up
/**
 * When any {@link RuntimeException} occurs, the connection should be closed, the developer should be notified on
 * this error and the admin should be warned.
 * 
 * @throws Exception
 *             Not expected to leave the method.
 */
@Test
public void whenARuntimeExceptionOccurredTheConnectionShouldBeClosedAndTheDeveloperBeWarned() throws Exception {
    final RuntimeException exampleRuntimeException = new RuntimeException(
            "The answer to everything could not be found.");
    cut.handleException(exampleRuntimeException);

    final ArgumentCaptor<Throwable> cause = ArgumentCaptor.forClass(Throwable.class);

    final ArgumentCaptor<String> developerMessage = ArgumentCaptor.forClass(String.class);
    verify(developer).unrecoverableProgrammingError(developerMessage.capture(), cause.capture());
    assertThat(developerMessage.getValue()).contains("runtime").contains("exception").contains("unhandled");
    assertThat(cause.getValue()).isSameAs(exampleRuntimeException);

    final ArgumentCaptor<String> adminMessage = ArgumentCaptor.forClass(String.class);
    verify(admin).unexpectedEvent(adminMessage.capture());
    assertThat(adminMessage.getValue()).contains("internal").contains("server").contains("client")
            .contains("connection").containsIgnoringCase("closing");

    verify(client).close();
}
 
Example 21
Project: java-coap   File: CoapServerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldPassMakeRequest_toMessaging() throws ExecutionException, InterruptedException {
    final CoapPacket req = newCoapPacket().get().uriPath("/test").build();
    final ArgumentCaptor<Callback> callback = ArgumentCaptor.forClass(Callback.class);

    //when
    final CompletableFuture<CoapPacket> resp = server.makeRequest(req);

    //then
    verify(msg).makeRequest(eq(req), callback.capture(), eq(TransportContext.NULL));
    assertFalse(resp.isDone());

    //verify callback
    callback.getValue().call(newCoapPacket().ack(Code.C400_BAD_REQUEST).build());
    assertTrue(resp.isDone());
    assertEquals(Code.C400_BAD_REQUEST, resp.get().getCode());
}
 
Example 22
Project: oscm   File: MarketplaceServiceLocalBeanTest.java   Source Code and License 6 votes vote down vote up
@Test
public void addMarketplaceToOrganization()
        throws NonUniqueBusinessKeyException {
    // given
    Marketplace mp = givenMarketplace();
    mp.setKey(123L);
    Organization org = new Organization();
    org.setKey(567L);
    ArgumentCaptor<MarketplaceToOrganization> mto = ArgumentCaptor
            .forClass(MarketplaceToOrganization.class);

    // when
    service.addMarketplaceToOrganization(mp, org);

    // then
    verify(service.ds, times(1)).persist(mto.capture());
    assertEquals(mp.getKey(), mto.getValue().getMarketplace().getKey());
    assertEquals(org.getKey(), mto.getValue().getOrganization().getKey());
}
 
Example 23
Project: crnk-framework   File: HttpRequestProcessorImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldNotifyWhenActionIsExeecuted() throws Exception {
	// GIVEN
	String path = "/actionResource/1/someAction";
	String requestType = "GET";

	ControllerRegistry controllerRegistry = new ControllerRegistry(null);
	QuerySpecAdapterBuilder queryAdapterBuilder =
			new QuerySpecAdapterBuilder(new DefaultQuerySpecDeserializer(), moduleRegistry);
	RequestDispatcher sut = new HttpRequestProcessorImpl(moduleRegistry, controllerRegistry, null, queryAdapterBuilder);

	// WHEN
	Map<String, Set<String>> parameters = new HashMap<>();
	sut.dispatchAction(path, "GET", parameters);

	// THEN

	ArgumentCaptor<DocumentFilterContext> filterContextCaptor = ArgumentCaptor.forClass(DocumentFilterContext.class);

	Mockito.verify(documentFilter, Mockito.times(1)).filter(filterContextCaptor.capture(), Mockito.any
			(DocumentFilterChain.class));
	DocumentFilterContext filterContext = filterContextCaptor.getValue();
	Assert.assertEquals("GET", filterContext.getMethod());
	Assert.assertTrue(filterContext.getJsonPath() instanceof ActionPath);
}
 
Example 24
Project: mux2fs   File: MirrorFsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testOpenFileHandleIsUnique()
		throws Exception {
	// Given
	FileHandleFiller filler = mock(FileHandleFiller.class);
	ArgumentCaptor<Integer> handleCaptor = ArgumentCaptor.forClass(Integer.class);
	doNothing().when(filler).setFileHandle(handleCaptor.capture());
	Path fooBar = mockPath("foo.bar");
	when(fileSystem.provider().newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)))).thenReturn(mock(FileChannel.class));
	// When
	int result = fs.open("foo.bar", filler);
	result += fs.open("foo.bar", filler);
	result += fs.open("foo.bar", filler);
	// Then
	assertThat(result).isEqualTo(SUCCESS);
	verify(filler, times(3)).setFileHandle(gt(0));
	verifyNoMoreInteractions(filler);
	verify(fileSystem.provider(), times(3)).newFileChannel(eq(fooBar), eq(set(StandardOpenOption.READ)));
	verifyNoMoreInteractions(fileSystem.provider());
	assertThat(handleCaptor.getAllValues()).hasSize(3).doesNotHaveDuplicates();
}
 
Example 25
Project: PeSanKita-android   File: DeliveryReceiptJobTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDelivery() throws IOException {
  SignalServiceMessageSender textSecureMessageSender = mock(SignalServiceMessageSender.class);
  long                    timestamp               = System.currentTimeMillis();

  DeliveryReceiptJob deliveryReceiptJob = new DeliveryReceiptJob(context,
                                                                 "+14152222222",
                                                                 timestamp, "foo");

  ObjectGraph objectGraph = ObjectGraph.create(new TestModule(textSecureMessageSender));
  objectGraph.inject(deliveryReceiptJob);

  deliveryReceiptJob.onRun();

  ArgumentCaptor<SignalServiceAddress> captor = ArgumentCaptor.forClass(SignalServiceAddress.class);
  verify(textSecureMessageSender).sendDeliveryReceipt(captor.capture(), eq(timestamp));

  assertTrue(captor.getValue().getRelay().get().equals("foo"));
  assertTrue(captor.getValue().getNumber().equals("+14152222222"));
}
 
Example 26
Project: android-mobile-engage-sdk   File: MobileEngageInternalTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAppLogout_requestManagerCalledWithCorrectRequestModel() {
    Map<String, Object> payload = createBasePayload();
    RequestModel expected = new RequestModel.Builder()
            .url(ENDPOINT_LOGOUT)
            .payload(payload)
            .headers(defaultHeaders)
            .build();

    ArgumentCaptor<RequestModel> captor = ArgumentCaptor.forClass(RequestModel.class);

    mobileEngage.appLogout();

    verify(manager).setDefaultHeaders(defaultHeaders);
    verify(manager).submit(captor.capture());

    RequestModel result = captor.getValue();
    assertRequestModels(expected, result);
}
 
Example 27
Project: theskeleton   File: S3ClientConfigTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testCreateBucket() throws Exception {
	ArgumentCaptor<Callable<List<String>>> argumentCaptor = ArgumentCaptor.forClass(Callable.class);
	when(executorService.schedule(argumentCaptor.capture(), anyLong(), any())).then(invocation -> {
		Callable<List<String>> callable = invocation.getArgument(0);
		callable.call();
		return null;
	});
	when(minioClient.bucketExists(eq("test1"))).thenReturn(true);
	when(minioClient.bucketExists(eq("test2"))).thenReturn(false);
	s3ClientConfig.createBuckets(minioClient, executorService, s3ClientProperties);
	verify(minioClient, times(2)).bucketExists(anyString());
	verify(minioClient).makeBucket(eq("test2"));
	verify(executorService).schedule(argumentCaptor.capture(), anyLong(), any());
	when(minioClient.bucketExists(anyString())).thenThrow(Exception.class);
	s3ClientConfig.createBuckets(minioClient, executorService, s3ClientProperties);
}
 
Example 28
Project: allure-java   File: AllureTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldAddLinks() throws Exception {
    io.qameta.allure.model.Link first = randomLink();
    io.qameta.allure.model.Link second = randomLink();
    io.qameta.allure.model.Link third = randomLink();

    Allure.addLinks(first, second);

    ArgumentCaptor<Consumer> captor = ArgumentCaptor.forClass(Consumer.class);
    verify(lifecycle, times(1)).updateTestCase(captor.capture());

    Consumer consumer = captor.getValue();
    TestResult result = new TestResult().withLinks(third);
    consumer.accept(result);

    assertThat(result)
            .isNotNull()
            .extracting(TestResult::getLinks)
            .containsExactly(Arrays.asList(third, first, second));
}
 
Example 29
Project: bluetooth-manager-tinyb   File: TinyBDeviceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testEnableConnectedNotifications() throws Exception {
    Notification<Boolean> notification = mock(Notification.class);
    ArgumentCaptor<BluetoothNotification> captor = ArgumentCaptor.forClass(BluetoothNotification.class);
    doNothing().when(bluetoothDevice).enableConnectedNotifications(captor.capture());

    tinyBDevice.enableConnectedNotifications(notification);

    verify(bluetoothDevice, times(1)).enableConnectedNotifications(captor.getValue());
    verifyNoMoreInteractions(bluetoothDevice, notification);

    captor.getValue().run(CONNECTED);
    verify(notification, times(1)).notify(CONNECTED);

    doThrow(RuntimeException.class).when(notification).notify(anyBoolean());
    captor.getValue().run(false);
    verify(notification, times(1)).notify(false);
}
 
Example 30
Project: elasticsearch_my   File: TransportWriteActionTests.java   Source Code and License 6 votes vote down vote up
public void testPrimaryWaitForRefresh() throws Exception {
    TestRequest request = new TestRequest();
    request.setRefreshPolicy(RefreshPolicy.WAIT_UNTIL);

    TestAction testAction = new TestAction();
    TransportWriteAction.WritePrimaryResult<TestRequest, TestResponse> result =
            testAction.shardOperationOnPrimary(request, indexShard);
    CapturingActionListener<TestResponse> listener = new CapturingActionListener<>();
    result.respond(listener);
    assertNull(listener.response); // Haven't reallresponded yet

    @SuppressWarnings({ "unchecked", "rawtypes" })
    ArgumentCaptor<Consumer<Boolean>> refreshListener = ArgumentCaptor.forClass((Class) Consumer.class);
    verify(indexShard, never()).refresh(any());
    verify(indexShard).addRefreshListener(any(), refreshListener.capture());

    // Now we can fire the listener manually and we'll get a response
    boolean forcedRefresh = randomBoolean();
    refreshListener.getValue().accept(forcedRefresh);
    assertNotNull(listener.response);
    assertNull(listener.failure);
    assertEquals(forcedRefresh, listener.response.forcedRefresh);
}
 
Example 31
Project: hashsdn-controller   File: DataTreeCohortIntegrationTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private static DOMDataTreeCandidate findCandidate(ArgumentCaptor<Collection> candidateCapture,
        YangInstanceIdentifier rootPath) {
    for (Object obj: candidateCapture.getValue()) {
        DOMDataTreeCandidate candidate = (DOMDataTreeCandidate)obj;
        if (rootPath.equals(candidate.getRootPath().getRootIdentifier())) {
            return candidate;
        }
    }

    return null;
}
 
Example 32
Project: q-mail   File: PgpMessageBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void buildCleartext__shouldSucceed() {
    cryptoStatusBuilder.setCryptoMode(CryptoMode.NO_CHOICE);
    pgpMessageBuilder.setCryptoStatus(cryptoStatusBuilder.build());

    Callback mockCallback = mock(Callback.class);
    pgpMessageBuilder.buildAsync(mockCallback);

    ArgumentCaptor<MimeMessage> captor = ArgumentCaptor.forClass(MimeMessage.class);
    verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false));
    verifyNoMoreInteractions(mockCallback);

    MimeMessage message = captor.getValue();
    assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL);
}
 
Example 33
Project: com.zsmartsystems.zigbee   File: ZigBeeNetworkManagerTest.java   Source Code and License 5 votes vote down vote up
private CommandInterface getCommandInterface() {
    CommandInterface commandInterface = Mockito.mock(CommandInterface.class);
    argumentPacket = ArgumentCaptor.forClass(ZToolPacket.class);
    argumentListener = ArgumentCaptor.forClass(SynchronousCommandListener.class);
    argumentTimeout = ArgumentCaptor.forClass(Long.class);
    try {
        Mockito.doNothing().when(commandInterface).sendSynchronousCommand(argumentPacket.capture(),
                argumentListener.capture(), argumentTimeout.capture());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return commandInterface;
}
 
Example 34
Project: verify-hub   File: IdpDisabledExceptionMapperTest.java   Source Code and License 5 votes vote down vote up
@Test
public void toResponse_shouldLogToEventSink() throws Exception {
    IdpDisabledException exception = new IdpDisabledException("my-entity");
    ArgumentCaptor<EventSinkHubEvent> captor = ArgumentCaptor.forClass(EventSinkHubEvent.class);

    exceptionMapper.toResponse(exception);

    verify(eventSinkProxy).logHubEvent(captor.capture());
    EventSinkHubEvent value = captor.getValue();
    assertThat(value.getOriginatingService()).isEqualTo(SERVICE_NAME);
    assertThat(value.getEventType()).isEqualTo(EventSinkHubEventConstants.EventTypes.ERROR_EVENT);
    assertThat(value.getSessionId()).isEqualTo(SESSION_ID.toString());
    assertThat(value.getDetails().containsKey(idp_entity_id)).as("Details should contain IDP id").isTrue();
}
 
Example 35
Project: hadoop   File: TestDnRespectsBlockReportSplitThreshold.java   Source Code and License 5 votes vote down vote up
/**
 * Test that if splitThreshold is zero, then we always get a separate
 * call per storage.
 */
@Test(timeout=300000)
public void testAlwaysSplit() throws IOException, InterruptedException {
  startUpCluster(0);
  NameNode nn = cluster.getNameNode();
  DataNode dn = cluster.getDataNodes().get(0);

  // Create a file with a few blocks.
  createFile(GenericTestUtils.getMethodName(), BLOCKS_IN_FILE);

  // Insert a spy object for the NN RPC.
  DatanodeProtocolClientSideTranslatorPB nnSpy =
      DataNodeTestUtils.spyOnBposToNN(dn, nn);

  // Trigger a block report so there is an interaction with the spy
  // object.
  DataNodeTestUtils.triggerBlockReport(dn);

  ArgumentCaptor<StorageBlockReport[]> captor =
      ArgumentCaptor.forClass(StorageBlockReport[].class);

  Mockito.verify(nnSpy, times(cluster.getStoragesPerDatanode())).blockReport(
      any(DatanodeRegistration.class),
      anyString(),
      captor.capture(),  Mockito.<BlockReportContext>anyObject());

  verifyCapturedArguments(captor, 1, BLOCKS_IN_FILE);
}
 
Example 36
Project: syndesis   File: CredentialsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldAcquireOAuth2Credentials() {
    final OAuth2ConnectionFactory<?> oauth2 = mock(OAuth2ConnectionFactory.class);
    @SuppressWarnings("unchecked")
    final Applicator<AccessGrant> applicator = mock(Applicator.class);
    when(locator.providerWithId("providerId"))
        .thenReturn(new OAuth2CredentialProvider<>("providerId", oauth2, applicator));

    when(oauth2.getScope()).thenReturn("scope");
    when(oauth2.generateState()).thenReturn("state-token");
    final OAuth2Operations operations = mock(OAuth2Operations.class);
    when(oauth2.getOAuthOperations()).thenReturn(operations);
    final ArgumentCaptor<OAuth2Parameters> parameters = ArgumentCaptor.forClass(OAuth2Parameters.class);
    when(operations.buildAuthorizeUrl(parameters.capture())).thenReturn("https://provider.io/oauth/authorize");

    final AcquisitionFlow acquisition = credentials.acquire("providerId", URI.create("https://syndesis.io/api/v1/"),
        URI.create("/ui#state"));

    final CredentialFlowState expectedFlowState = new OAuth2CredentialFlowState.Builder().key("state-token")
        .providerId("providerId").redirectUrl("https://provider.io/oauth/authorize")
        .returnUrl(URI.create("/ui#state")).build();

    final AcquisitionFlow expected = new AcquisitionFlow.Builder().type(Type.OAUTH2)
        .redirectUrl("https://provider.io/oauth/authorize").state(expectedFlowState).build();
    assertThat(acquisition).isEqualTo(expected);

    final OAuth2Parameters capturedParameters = parameters.getValue();
    assertThat(capturedParameters.getRedirectUri()).isEqualTo("https://syndesis.io/api/v1/credentials/callback");
    assertThat(capturedParameters.getScope()).isEqualTo("scope");
    assertThat(capturedParameters.getState()).isEqualTo("state-token");
}
 
Example 37
Project: RxFirebase2   File: RxFirebaseDatabaseTest.java   Source Code and License 5 votes vote down vote up
@Before public void setup() {
  MockitoAnnotations.initMocks(this);

  childEventListener = ArgumentCaptor.forClass(ChildEventListener.class);
  valueEventListener = ArgumentCaptor.forClass(ValueEventListener.class);
  transactionHandler = ArgumentCaptor.forClass(Transaction.Handler.class);
  onCompleteListener = ArgumentCaptor.forClass(OnCompleteListener.class);
}
 
Example 38
Project: firebase-chat-android-architecture-components   File: UserViewModelTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCallRepo() {
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    userViewModel.getUser().observeForever(mock(Observer.class));
    userViewModel.setLogin("abc");
    verify(userRepository).loadUser(captor.capture());
    assertThat(captor.getValue(), is("abc"));
    reset(userRepository);
    userViewModel.setLogin("ddd");
    verify(userRepository).loadUser(captor.capture());
    assertThat(captor.getValue(), is("ddd"));
}
 
Example 39
Project: iotdb-jdbc   File: TsFilePrepareStatementTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("resource")
@Test
public void oneBooleanArgument() throws Exception {
	String sql = "SELECT status, temperature FROM root.ln.wf01.wt01 WHERE temperature < ? and time > 2017-11-1 0:13:00";
	TsfilePrepareStatement ps = new TsfilePrepareStatement(connection, client, sessHandle, sql);
	ps.setBoolean(1, false);
	ps.execute();
	ArgumentCaptor<TSExecuteStatementReq> argument = ArgumentCaptor.forClass(TSExecuteStatementReq.class);
	verify(client).executeStatement(argument.capture());
	assertEquals("SELECT status, temperature FROM root.ln.wf01.wt01 WHERE temperature < false and time > 2017-11-1 0:13:00", argument.getValue().getStatement());
}
 
Example 40
Project: killbill-easytax-plugin   File: EasyTaxServletTests.java   Source Code and License 5 votes vote down vote up
@Test(groups = "fast")
public void addTaxCode() throws IOException, ServletException, SQLException {
    // given
    byte[] data = "{\"tax_rate\":\"0.15\",\"valid_from_date\":\"2017-01-01T12:00:00Z\"}"
            .getBytes("UTF-8");
    ByteArrayInputStream byis = new ByteArrayInputStream(data);
    ByteArrayOutputStream byos = givenDefaultServletCall("POST", "/taxCodes/NZ/memory-use/GST",
            byis, data.length, EasyTaxServlet.APPLICATION_JSON_UTF8);
    givenPermissions(TEST_USER, TEST_PASSWORD, TEST_PERMISSIONS);

    // when
    servlet.service(req, res);

    // then
    thenAuthenticatedAs(TEST_USER, TEST_PASSWORD);
    thenDefaultResponse(201, null);
    then(res).should().setHeader(HttpHeaders.LOCATION,
            "/plugins/killbill-easytax/taxCodes/NZ/memory-use/GST");

    ArgumentCaptor<EasyTaxTaxCode> taxCodeCaptor = ArgumentCaptor
            .forClass(EasyTaxTaxCode.class);
    then(dao).should().saveTaxCode(taxCodeCaptor.capture());

    assertEquals(byos.size(), 0, "Response body content");
    EasyTaxTaxCode saved = taxCodeCaptor.getValue();
    assertEquals(saved.getCreatedDate(), now);
    assertEquals(saved.getKbTenantId(), tenantId);
    assertEquals(saved.getTaxZone(), "NZ");
    assertEquals(saved.getProductName(), "memory-use");
    assertEquals(saved.getTaxCode(), "GST");
    assertDateTimeEquals(saved.getValidFromDate(),
            new DateTime(2017, 1, 1, 12, 0, 0, DateTimeZone.UTC), "Valid from date");
    assertNull(saved.getValidToDate(), "Valid to date");
}