java类org.mockito.ArgumentCaptor的实例源码

RegisterInterest61Test.java 文件源码 项目:monarch 阅读 90 收藏 0 点赞 0 评论 0
@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);
}
MirrorFsTest.java 文件源码 项目:mux2fs 阅读 32 收藏 0 点赞 0 评论 0
@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);
}
Cycle3MatchRequestSentStateControllerTest.java 文件源码 项目:verify-hub 阅读 26 收藏 0 点赞 0 评论 0
@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);
}
MessageCryptoHelperTest.java 文件源码 项目:q-mail 阅读 26 收藏 0 点赞 0 评论 0
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);
}
EventSinkHubEventLoggerTest.java 文件源码 项目:verify-hub 阅读 27 收藏 0 点赞 0 评论 0
@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);
}
SmartLogTest.java 文件源码 项目:smartlog 阅读 32 收藏 0 点赞 0 评论 0
@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);
}
OverlayViewTest.java 文件源码 项目:Phial 阅读 24 收藏 0 点赞 0 评论 0
@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());
}
TinyBAdapterTest.java 文件源码 项目:bluetooth-manager-tinyb 阅读 23 收藏 0 点赞 0 评论 0
@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);
}
APPAuthenticationServiceBeanIT.java 文件源码 项目:oscm-app 阅读 24 收藏 0 点赞 0 评论 0
@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());
}
PricingServiceBeanTest.java 文件源码 项目:oscm 阅读 23 收藏 0 点赞 0 评论 0
@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());
}
RepositoryFilterTest.java 文件源码 项目:crnk-framework 阅读 28 收藏 0 点赞 0 评论 0
@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));
}
Bug4513Test.java 文件源码 项目:hashsdn-controller 阅读 26 收藏 0 点赞 0 评论 0
@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());
}
MonitoredAspectTest.java 文件源码 项目:waggle-dance 阅读 31 收藏 0 点赞 0 评论 0
@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"));
}
SmtpSessionTest.java 文件源码 项目:NioSmtpClient 阅读 28 收藏 0 点赞 0 评论 0
@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");
}
LoggingInterceptorTest.java 文件源码 项目:GitHub 阅读 27 收藏 0 点赞 0 评论 0
@Test
public void testLogArray() 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);

    final String[] array = new String[]{"Buenos Aires", "Córdoba", "La Plata"};
    view.twoArgs(array, "B");
    verify(logger).log(anyInt(), anyString(), msgCaptor.capture());

    assertThat(msgCaptor.getValue())
            .matches("twoArgs\\(\\{String\\[\\]\\[3\\]@[\\da-f]{1,8}\\} \\"
                    + "[Buenos Aires, Córdoba, La Plata\\], B\\)");
}
LoggingInterceptorTest.java 文件源码 项目:GitHub 阅读 23 收藏 0 点赞 0 评论 0
@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"
                    + "\\)");
}
StateBuilder.java 文件源码 项目:asaf-project 阅读 29 收藏 0 点赞 0 评论 0
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;
    }
UpdateUserCtrlTest.java 文件源码 项目:oscm 阅读 26 收藏 0 点赞 0 评论 0
@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());
}
IdentityServiceBeanMailSendingTest.java 文件源码 项目:oscm 阅读 26 收藏 0 点赞 0 评论 0
@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]);
}
UpdateMarketplaceBeanTest.java 文件源码 项目:oscm 阅读 21 收藏 0 点赞 0 评论 0
@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 }));
}
ExceptionHandlerTest.java 文件源码 项目:trading4j 阅读 25 收藏 0 点赞 0 评论 0
/**
 * 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();
}
CoapServerTest.java 文件源码 项目:java-coap 阅读 27 收藏 0 点赞 0 评论 0
@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());
}
MarketplaceServiceLocalBeanTest.java 文件源码 项目:oscm 阅读 27 收藏 0 点赞 0 评论 0
@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());
}
HttpRequestProcessorImplTest.java 文件源码 项目:crnk-framework 阅读 25 收藏 0 点赞 0 评论 0
@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);
}
MirrorFsTest.java 文件源码 项目:mux2fs 阅读 31 收藏 0 点赞 0 评论 0
@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();
}
DeliveryReceiptJobTest.java 文件源码 项目:PeSanKita-android 阅读 31 收藏 0 点赞 0 评论 0
@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"));
}
MobileEngageInternalTest.java 文件源码 项目:android-mobile-engage-sdk 阅读 26 收藏 0 点赞 0 评论 0
@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);
}
S3ClientConfigTest.java 文件源码 项目:theskeleton 阅读 22 收藏 0 点赞 0 评论 0
@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);
}
AllureTest.java 文件源码 项目:allure-java 阅读 25 收藏 0 点赞 0 评论 0
@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));
}
TinyBDeviceTest.java 文件源码 项目:bluetooth-manager-tinyb 阅读 24 收藏 0 点赞 0 评论 0
@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);
}


问题


面经


文章

微信
公众号

扫码关注公众号