Java org.mockito.ArgumentCaptor 代码实例

・1 分钟阅读

以下是展示如何使用org.mockito.ArgumentCaptor的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Test
@SuppressWarnings("unchecked")
public void testConnect() throws Exception {
  ArgumentCaptor<Configuration> captor = ArgumentCaptor.forClass(Configuration.class);
  CompletableFuture<Boolean> botStartedFuture = new CompletableFuture<>();
  doAnswer(invocation -> {
    botStartedFuture.complete(true);
    botShutdownLatch.await();
    return null;
  }).when(pircBotX).startBot();
  instance.connect();
  botStartedFuture.get(TIMEOUT, TIMEOUT_UNIT);
  verify(pircBotX).startBot();
  verify(pircBotXFactory).createPircBotX(captor.capture());
  Configuration configuration = captor.getValue();
  assertThat(configuration.getName(), is(CHAT_USER_NAME));
  assertThat(configuration.getLogin(), is(CHAT_USER_NAME));
  assertThat(configuration.getRealName(), is(CHAT_USER_NAME));
  assertThat(configuration.getServerHostname(), is(LOOPBACK_ADDRESS.getHostAddress()));
  assertThat(configuration.getServerPort(), is(IRC_SERVER_PORT));
}
 

实例 2


@SuppressWarnings("unchecked")
@Test
public void testContentTypes() throws Exception {
    // For each valid type of name
    for (int i = 0; i < names.length; i++) {
        BinaryStoreManager binaryStoreManager = mock(BinaryStoreManager.class);
        dbsw = new DefaultBinaryStoreWriter(binaryStoreManager, when);
        fileInfo = createFileInfo();
        fileInfo.setFileName(names[i]);
        fileInfo.setContentType(null);
        ReadStream<Buffer> readStream = mock(ReadStream.class);
        FutureCallback<FileInfo> callback = mock(FutureCallback.class);
        ArgumentCaptor<Handler> endHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
        ArgumentCaptor<FileInfo> fileInfoArgumentCaptor = ArgumentCaptor.forClass(FileInfo.class);
        // We try and write and capture the end handler
        Promise<FileInfo> p = dbsw.write(fileInfo, readStream);
        verify(readStream).endHandler(endHandlerCaptor.capture());
        // We then call the end handler
        endHandlerCaptor.getValue().handle(null);
        // and expect binarystoremanager to have the storefile method called with a fileinfo object that has the
        // correct contentype on it.
        verify(binaryStoreManager).storeFile(fileInfoArgumentCaptor.capture());
        assertEquals(types[i], fileInfoArgumentCaptor.getValue().getContentType());
    }
}
 

实例 3


@Before 
public void setup() {
        principal = ArgumentCaptor.forClass(Object.class);
        action = ArgumentCaptor.forClass(Action.class);
        modelNode = ArgumentCaptor.forClass(Node.class);
        triple = ArgumentCaptor.forClass(Triple.class);
}
 

实例 4


@Test
public void testSendDirectWithTimeoutOk() {
        Mockito.when(this.clientOutboundChannel.send(Matchers.any(WampMessage.class),
                        Matchers.anyLong())).thenReturn(true);
        this.eventMessenger.setSendTimeout(11);
        EventMessage eventMessage = new EventMessage("topic", "1");
        eventMessage.setWebSocketSessionId("ws1");
        this.eventMessenger.sendDirect(eventMessage);
        ArgumentCaptor<Long> timeOutArgument = ArgumentCaptor.forClass(Long.class);
        Mockito.verify(this.clientOutboundChannel, Mockito.times(1))
                        .send(this.messageCaptor.capture(), timeOutArgument.capture());
        Mockito.verifyZeroInteractions(this.brokerChannel);
        assertThat(timeOutArgument.getValue()).isEqualTo(11);
        EventMessage msg = this.messageCaptor.getValue();
        assertThat(msg.getDestination()).isEqualTo("topic");
        assertThat(msg.getEvent()).isEqualTo("1");
        assertThat(msg.getWebSocketSessionId()).isEqualTo("ws1");
        assertThat(msg.getExcludeWebSocketSessionIds()).isNull();
        assertThat(msg.getEligibleWebSocketSessionIds()).isNull();
}
 

实例 5


@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void Merger_Gets_Called() {
    Merger<Entry<Integer, Integer>> merger = mock(Merger.class);
    doReturn(true).when(merger).merge(any(Entry.class), any(Entry.class));
    ArgumentCaptor<Entry> entry1 = ArgumentCaptor.forClass(Entry.class);
    ArgumentCaptor<Entry> entry2 = ArgumentCaptor.forClass(Entry.class);
    PersistentMap<Integer, Integer> map = emptyMap();
    map = map.merge(1, 1, merger);
    assertThat(map.get(1), equalTo(1));
    verify(merger).insert(entry1.capture());
    assertEntry(entry1, 1, 1);
    map = map.merge(1, 2, merger);
    assertThat(map.get(1), equalTo(2));
    verify(merger).merge(entry1.capture(), entry2.capture());
    assertEntry(entry1, 1, 1);
    assertEntry(entry2, 1, 2);
    map = map.dissoc(1, merger);
    assertThat(map.get(1), nullValue());
    verify(merger).delete(entry2.capture());
    assertEntry(entry2, 1, 2);
}
 

实例 6


@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void Merge_All_Map() {
    PersistentMap<Integer, Integer> map = emptyMap().assoc(1, 1);
    Map<Integer, Integer> ints = ImmutableMap.of(1, 2, 3, 3);
    Map<Integer, Integer> expected = ImmutableMap.of(1, 2, 3, 3);
    Merger<Entry<Integer, Integer>> merger = mock(Merger.class);
    doReturn(true).when(merger).merge(any(Entry.class), any(Entry.class));
    map = map.mergeAll(ints, merger);
    assertThat(map.asMap(), equalTo(expected));
    ArgumentCaptor<Entry> entry1 = ArgumentCaptor.forClass(Entry.class);
    ArgumentCaptor<Entry> entry2 = ArgumentCaptor.forClass(Entry.class);
    verify(merger).merge(entry1.capture(), entry2.capture());
    assertEntry(entry1, 1, 1);
    assertEntry(entry2, 1, 2);
    verify(merger).insert(entry1.capture());
    assertEntry(entry1,3, 3);
}
 

实例 7


@Test
public void simpleTest() throws Exception {
    final MockInputStream input = mockInputStream("AaBbAaBbcdefF");
    expect = new ExpectBuilder()
            .withExceptionOnFailure()
            .withTimeout(SMALL_TIMEOUT, TimeUnit.MILLISECONDS)
            .withInputs(input.getStream())
            .build();
    input.waitUntilReady();
    final Action<Result> action1 = mock(Action.class);
    final Action<MultiResult> action2 = mock(Action.class);
    final Action<Result> action3 = mock(Action.class);
    final ArgumentCaptor<Result> result1 = ArgumentCaptor.forClass(Result.class);
    final ArgumentCaptor<MultiResult> result2 = ArgumentCaptor.forClass(MultiResult.class);
    final ArgumentCaptor<Result> result3 = ArgumentCaptor.forClass(Result.class);
    doNothing().when(action1).apply(result1.capture());
    doNothing().when(action2).apply(result2.capture());
    doNothing().when(action3).apply(result3.capture());
    final Result result = expect.interact()
            .when(contains("a")).then(action1)
            .when(allOf(contains("b"))).then(action2)
            .when(contains("XXX")).then(action3)
            .until(contains("ef"));
    assertEquals(result.getBefore(), "cd");
    assertEquals(result1.getValue().getBefore(), "A");
    assertEquals(result2.getValue().getBefore(), "AaB");
    verify(action1, Mockito.times(2)).apply(any(Result.class));
    verify(action2, Mockito.times(2)).apply(any(MultiResult.class));
    verifyNoMoreInteractions(action3);
}
 

实例 8


public void testReceiveChallenges() throws Exception {
  final SmsListener smsListener = new SmsListener();
  for (int i = 0; i < CHALLENGES.length; i++) {
    final String CHALLENGE     = CHALLENGES[i];
    final String CHALLENGE_SMS = SmsListenerTest.CHALLENGE_SMS[i];
    final Context                mockContext     = mock(Context.class);
    final SharedPreferences      mockPreferences = mock(SharedPreferences.class);
    final ArgumentCaptor<Intent> intentCaptor    = ArgumentCaptor.forClass(Intent.class);
    when(mockContext.getPackageName()).thenReturn(getContext().getPackageName());
    when(mockContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mockPreferences);
    when(mockPreferences.getBoolean(contains("pref_verifying"), anyBoolean())).thenReturn(true);
    try {
      smsListener.onReceive(mockContext, SmsUtil.buildSmsReceivedIntent("15555555555", (CHALLENGE_SMS)));
    } catch (IllegalStateException e) {
      Log.d(getClass().getName(), "some api levels are picky with abortBroadcast()");
    }
    verify(mockContext, times(1)).sendBroadcast(intentCaptor.capture());
    final Intent sendIntent = intentCaptor.getValue();
    assertTrue(sendIntent.getAction().equals(RegistrationService.CHALLENGE_EVENT));
    assertTrue(sendIntent.getStringExtra(RegistrationService.CHALLENGE_EXTRA).equals(CHALLENGE));
  }
}
 

实例 9


@Test
@SuppressWarnings("unchecked")
public void shutdownhook_should_send_all_messages_in_buffer_to_kafka() {
    HosebirdReader tr = mock(HosebirdReader.class);
    tr.setLogger(this.logger);
    StatsReporter stats = new StatsReporter();
    tr.metrics = new Metrics(stats.getStatsTracker());
    tr.metrics.shutdown = mock(Meter.class);
    tr.metrics.read = mock(Meter.class);
    doCallRealMethod().when(tr).addShutdownHook(any(Client.class), any(LinkedBlockingQueue.class), anyString(), any(Producer.class));
    doCallRealMethod().when(tr).readAndSend(any(LinkedBlockingQueue.class), anyString(), any(Producer.class), any(ReadAndSendPredicate.class));
    LinkedBlockingQueue buffer = new LinkedBlockingQueue(5);
    buffer.add("1");
    buffer.add("2");
    buffer.add("3");
    buffer.add("4");
    buffer.add("5");
    KafkaProducer<String, String> producer = mock(KafkaProducer.class);
    tr.addShutdownHook(client, buffer, "TOPIC", producer);
    ArgumentCaptor<Thread> threadCaptor = ArgumentCaptor.forClass(Thread.class);
    verify(tr).runtimeAddShutdownHook(threadCaptor.capture());
    Thread thread = threadCaptor.getValue();
    thread.run();
    try {
        thread.join();
    } catch(Exception e) {
        assertNull(e);
    }
    assertEquals(0, buffer.size());
    verify(producer, times(5)).send(any(ProducerRecord.class), any(Callback.class));
    verify(client).stop();
}
 

实例 10


@Test
@SuppressWarnings("unchecked")
public void shutdownhook_should_end_if_exception_thrown() {
    HosebirdReader tr = mock(HosebirdReader.class);
    tr.setLogger(this.logger);
    StatsReporter stats = new StatsReporter();
    tr.metrics = new Metrics(stats.getStatsTracker());
    tr.metrics.shutdown = mock(Meter.class);
    doCallRealMethod().when(tr).addShutdownHook(any(Client.class), any(LinkedBlockingQueue.class), anyString(), any(Producer.class));
    doThrow(new RuntimeException("ERROR")).when(tr).readAndSend(any(LinkedBlockingQueue.class), anyString(), any(Producer.class), any(ReadAndSendPredicate.class));
    LinkedBlockingQueue buffer = new LinkedBlockingQueue(1);
    buffer.add("1");
    KafkaProducer<String, String> producer = mock(KafkaProducer.class);
    tr.addShutdownHook(client, buffer, "TOPIC", producer);
    ArgumentCaptor<Thread> threadCaptor = ArgumentCaptor.forClass(Thread.class);
    verify(tr).runtimeAddShutdownHook(threadCaptor.capture());
    Thread thread = threadCaptor.getValue();
    try {
        thread.run();
    } catch(Exception e) {
        assertEquals("ERROR", e.getMessage());
    }
    verify(producer, times(0)).send(any(ProducerRecord.class), any(Callback.class));
    assertEquals(1, buffer.size());
}
 

实例 11


private void onGameTypeAdded(GameTypeBean gameTypeBean) {
  ArgumentCaptor<MapChangeListener<String, GameTypeBean>> argument = ArgumentCaptor.forClass(MapChangeListener.class);
  verify(instance.gameService, atLeastOnce()).addOnGameTypeInfoListener(argument.capture());
  MapChangeListener<String, GameTypeBean> listener = argument.getValue();
  @SuppressWarnings("unchecked")
  Change<String, GameTypeBean> change = mock(Change.class);
  when(change.wasAdded()).thenReturn(true);
  when(change.getValueAdded()).thenReturn(gameTypeBean);
  listener.onChanged(change);
}
 

实例 12


@Test
public void testMergeNotMatch() {
    final Record nonMatchingRecord = TestBeanFactory.createRecordBuilder()
            .setMetrics(ImmutableMap.of(
                    "does_not_match",
                    TestBeanFactory.createMetric()))
            .build();
    final Source mergingSource = _mappingSourceBuilder.build();
    mergingSource.attach(_mockObserver);
    notify(_mockSource, nonMatchingRecord);
    final ArgumentCaptor<Record> argument = ArgumentCaptor.forClass(Record.class);
    Mockito.verify(_mockObserver).notify(Matchers.same(mergingSource), argument.capture());
    final Record actualRecord = argument.getValue();
    Assert.assertTrue(
            String.format("expected=%s, actual=%s", nonMatchingRecord, actualRecord),
            UnorderedRecordEquality.equals(nonMatchingRecord, actualRecord));
}
 

实例 13


@Test
public void testReplaceWithCapture() {
    final Record matchingRecord = TestBeanFactory.createRecordBuilder()
            .setAnnotations(Collections.singletonMap("key", "value"))
            .setMetrics(ImmutableMap.of(
                    "cat/sheep/dog",
                    TestBeanFactory.createMetricBuilder()
                            .setType(MetricType.GAUGE)
                            .setValues(Collections.singletonList(
                                    new Quantity.Builder()
                                            .setValue(3.14d)
                                            .setUnit(Unit.BYTE)
                                            .build()))
                            .build()))
            .build();
    final Source mergingSource = _mappingSourceBuilder.build();
    mergingSource.attach(_mockObserver);
    notify(_mockSource, matchingRecord);
    final ArgumentCaptor<Record> argument = ArgumentCaptor.forClass(Record.class);
    Mockito.verify(_mockObserver).notify(Matchers.same(mergingSource), argument.capture());
    final Record actualRecord = argument.getValue();
    final Record expectedRecord = TestBeanFactory.createRecordBuilder()
            .setAnnotations(matchingRecord.getAnnotations())
            .setTime(matchingRecord.getTime())
            .setMetrics(ImmutableMap.of(
                    "cat/dog/sheep",
                    TestBeanFactory.createMetricBuilder()
                            .setType(MetricType.GAUGE)
                            .setValues(ImmutableList.of(
                                    new Quantity.Builder()
                                            .setValue(3.14d)
                                            .setUnit(Unit.BYTE)
                                            .build()))
                            .build()))
            .build();
    Assert.assertTrue(
            String.format("expected=%s, actual=%s", expectedRecord, actualRecord),
            UnorderedRecordEquality.equals(expectedRecord, actualRecord));
}
 

实例 14


@Test
public void registerUserAccount_NormalRegistrationAndEmailExists_ShouldRenderRegistrationFormWithFieldError() throws Exception {
    when(userServiceMock.registerNewUserAccount(isA(RegistrationForm.class))).thenThrow(new DuplicateEmailException(""));
    mockMvc.perform(post("/user/register")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .param(WebTestConstants.FORM_FIELD_EMAIL, EMAIL)
            .param(WebTestConstants.FORM_FIELD_FIRST_NAME, FIRST_NAME)
            .param(WebTestConstants.FORM_FIELD_LAST_NAME, LAST_NAME)
            .param(WebTestConstants.FORM_FIELD_PASSWORD, PASSWORD)
            .param(WebTestConstants.FORM_FIELD_PASSWORD_VERIFICATION, PASSWORD)
            .sessionAttr(WebTestConstants.SESSION_ATTRIBUTE_USER_FORM, new RegistrationForm())
    )
            .andExpect(status().isOk())
            .andExpect(view().name("user/registrationForm"))
            .andExpect(forwardedUrl("/WEB-INF/jsp/user/registrationForm.jsp"))
            .andExpect(model().attribute(WebTestConstants.MODEL_ATTRIBUTE_USER_FORM, allOf(
                    hasProperty(WebTestConstants.FORM_FIELD_EMAIL, is(EMAIL)),
                    hasProperty(WebTestConstants.FORM_FIELD_FIRST_NAME, is(FIRST_NAME)),
                    hasProperty(WebTestConstants.FORM_FIELD_LAST_NAME, is(LAST_NAME)),
                    hasProperty(WebTestConstants.FORM_FIELD_PASSWORD, is(PASSWORD)),
                    hasProperty(WebTestConstants.FORM_FIELD_PASSWORD, is(PASSWORD)),
                    hasProperty(WebTestConstants.FORM_FIELD_SIGN_IN_PROVIDER, isEmptyOrNullString())
            )))
            .andExpect(model().attributeHasFieldErrors(WebTestConstants.MODEL_ATTRIBUTE_USER_FORM, WebTestConstants.FORM_FIELD_EMAIL));
    assertThat(SecurityContextHolder.getContext()).userIsAnonymous();
    ArgumentCaptor<RegistrationForm> registrationFormArgument = ArgumentCaptor.forClass(RegistrationForm.class);
    verify(userServiceMock, times(1)).registerNewUserAccount(registrationFormArgument.capture());
    verifyNoMoreInteractions(userServiceMock);
    RegistrationForm formObject = registrationFormArgument.getValue();
    assertThatRegistrationForm(formObject)
            .isNormalRegistration()
            .hasEmail(EMAIL)
            .hasFirstName(FIRST_NAME)
            .hasLastName(LAST_NAME)
            .hasPassword(PASSWORD)
            .hasPasswordVerification(PASSWORD);
}
 

实例 15


@Test
public void registerUserAccount_NormalRegistration_ShouldCreateNewUserAccountAndRenderHomePage() throws Exception {
    User registered = new UserBuilder()
            .id(1L)
            .email(EMAIL)
            .firstName(FIRST_NAME)
            .lastName(LAST_NAME)
            .password(PASSWORD)
            .build();
    when(userServiceMock.registerNewUserAccount(isA(RegistrationForm.class))).thenReturn(registered);
    mockMvc.perform(post("/user/register")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .param(WebTestConstants.FORM_FIELD_EMAIL, EMAIL)
            .param(WebTestConstants.FORM_FIELD_FIRST_NAME, FIRST_NAME)
            .param(WebTestConstants.FORM_FIELD_LAST_NAME, LAST_NAME)
            .param(WebTestConstants.FORM_FIELD_PASSWORD, PASSWORD)
            .param(WebTestConstants.FORM_FIELD_PASSWORD_VERIFICATION, PASSWORD)
            .sessionAttr(WebTestConstants.SESSION_ATTRIBUTE_USER_FORM, new RegistrationForm())
    )
            .andExpect(status().isMovedTemporarily())
            .andExpect(redirectedUrl("/"));
    assertThat(SecurityContextHolder.getContext())
            .loggedInUserIs(registered)
            .loggedInUserHasPassword(registered.getPassword())
            .loggedInUserIsRegisteredByUsingNormalRegistration();
    ArgumentCaptor<RegistrationForm> registrationFormArgument = ArgumentCaptor.forClass(RegistrationForm.class);
    verify(userServiceMock, times(1)).registerNewUserAccount(registrationFormArgument.capture());
    verifyNoMoreInteractions(userServiceMock);
    RegistrationForm formObject = registrationFormArgument.getValue();
    assertThatRegistrationForm(formObject)
            .isNormalRegistration()
            .hasEmail(EMAIL)
            .hasFirstName(FIRST_NAME)
            .hasLastName(LAST_NAME)
            .hasPassword(PASSWORD)
            .hasPasswordVerification(PASSWORD);
}
 
讨论
淘淘あ西西 profile image