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

The following examples show how to use org.mockito.ArgumentCaptor#getValue() . 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 File: PrivateStorageMigrationTest.java    From besu with Apache License 2.0 7 votes vote down vote up
@Test
public void migrationOnlyProcessRequiredTransactions() {
  final List<Transaction> transactions = new ArrayList<>();
  transactions.add(publicTransaction());
  transactions.add(createPrivacyMarkerTransaction());
  transactions.add(publicTransaction());

  mockBlockchainWithTransactionsInABlock(transactions);

  migration.migratePrivateStorage();

  final ArgumentCaptor<List> txsCaptor = ArgumentCaptor.forClass(List.class);

  verify(privateMigrationBlockProcessor)
      .processBlock(any(), any(), any(), txsCaptor.capture(), any());

  // won't process transaction after PMT, that's why we only process 2 txs
  final List<Transaction> processedTxs = txsCaptor.getValue();
  assertThat(processedTxs).hasSize(2);
}
 
Example 2
Source File: ClientCallImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void advertisedEncodingsAreSent() {
  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      MoreExecutors.directExecutor(),
      baseCallOptions,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      false /* retryEnabled */)
          .setDecompressorRegistry(decompressorRegistry);

  call.start(callListener, new Metadata());

  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
  verify(transport).newStream(eq(method), metadataCaptor.capture(), same(baseCallOptions));
  Metadata actual = metadataCaptor.getValue();

  // there should only be one.
  Set<String> acceptedEncodings = ImmutableSet.of(
      new String(actual.get(GrpcUtil.MESSAGE_ACCEPT_ENCODING_KEY), GrpcUtil.US_ASCII));
  assertEquals(decompressorRegistry.getAdvertisedMessageEncodings(), acceptedEncodings);
}
 
Example 3
Source File: ChatCommandsPluginTest.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testPlayerSkillLookup() throws IOException
{
	Player player = mock(Player.class);
	when(player.getName()).thenReturn(PLAYER_NAME);
	when(client.getLocalPlayer()).thenReturn(player);

	when(chatCommandsConfig.lvl()).thenReturn(true);
	ArgumentCaptor<BiConsumer<ChatMessage, String>> captor = ArgumentCaptor.forClass(BiConsumer.class);
	verify(chatCommandManager).registerCommandAsync(eq("!lvl"), captor.capture());
	BiConsumer<ChatMessage, String> value = captor.getValue();

	SingleHiscoreSkillResult skillResult = new SingleHiscoreSkillResult();
	skillResult.setPlayer(PLAYER_NAME);
	skillResult.setSkill(new Skill(10, 1000, -1));

	when(hiscoreClient.lookup(PLAYER_NAME, HiscoreSkill.ZULRAH, null)).thenReturn(skillResult);

	MessageNode messageNode = mock(MessageNode.class);

	ChatMessage chatMessage = new ChatMessage();
	chatMessage.setType(ChatMessageType.PUBLICCHAT);
	chatMessage.setName(PLAYER_NAME);
	chatMessage.setMessageNode(messageNode);
	value.accept(chatMessage, "!lvl zulrah");

	verify(messageNode).setRuneLiteFormatMessage("<colNORMAL>Level <colHIGHLIGHT>Zulrah: 1000<colNORMAL> Rank: <colHIGHLIGHT>10");
}
 
Example 4
Source File: TppControllerTest.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@Test
void getRandomTppId() {
    when(dataRestClient.branchId(any())).thenReturn(ResponseEntity.ok("DE_123"));
    ResponseEntity<String> result = tppController.getRandomTppId("DE");
    ArgumentCaptor<BbanStructure> captor = ArgumentCaptor.forClass(BbanStructure.class);
    verify(dataRestClient, times(1)).branchId(captor.capture());
    BbanStructure value = captor.getValue();
    assertEquals("DE", value.getCountryPrefix());
    assertEquals(8, value.getLength());
    assertEquals(BbanStructure.EntryType.N, value.getEntryType());
    assertEquals(HttpStatus.OK, result.getStatusCode());
}
 
Example 5
Source File: DefaultHttp2ConnectionDecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Calls the decode method on the handler and gets back the captured internal listener
 */
private Http2FrameListener decode() throws Exception {
    ArgumentCaptor<Http2FrameListener> internalListener = ArgumentCaptor.forClass(Http2FrameListener.class);
    doNothing().when(reader).readFrame(eq(ctx), any(ByteBuf.class), internalListener.capture());
    decoder.decodeFrame(ctx, EMPTY_BUFFER, Collections.emptyList());
    return internalListener.getValue();
}
 
Example 6
Source File: StandardWebSocketClientTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void clientEndpointConfig() throws Exception {

	URI uri = new URI("ws://localhost/abc");
	List<String> protocols = Collections.singletonList("abc");
	this.headers.setSecWebSocketProtocol(protocols);

	this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get();

	ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class);
	verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class));
	ClientEndpointConfig endpointConfig = captor.getValue();

	assertEquals(protocols, endpointConfig.getPreferredSubprotocols());
}
 
Example 7
Source File: AbstractClientServiceTest.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeWithDoneOnException() throws Exception {
    InvokeContext invokeCtx = new InvokeContext();
    invokeCtx.put(InvokeContext.CRC_SWITCH, false);
    ArgumentCaptor<InvokeCallback> callbackArg = ArgumentCaptor.forClass(InvokeCallback.class);
    PingRequest request = TestUtils.createPingRequest();

    MockRpcResponseClosure<ErrorResponse> done = new MockRpcResponseClosure<>();
    Future<Message> future = this.clientService.invokeWithDone(this.endpoint, request, invokeCtx, done, -1);
    Mockito.verify(this.rpcClient).invokeAsync(eq(this.endpoint), eq(request), eq(invokeCtx),
        callbackArg.capture(), eq((long) this.rpcOptions.getRpcDefaultTimeout()));
    InvokeCallback cb = callbackArg.getValue();
    assertNotNull(cb);
    assertNotNull(future);

    assertNull(done.getResponse());
    assertNull(done.status);
    assertFalse(future.isDone());

    cb.complete(null, new InvokeTimeoutException());

    try {
        future.get();
        fail();
    } catch (ExecutionException e) {
        assertTrue(e.getCause() instanceof InvokeTimeoutException);
    }

    done.latch.await();
    assertNotNull(done.status);
    assertEquals(RaftError.ETIMEDOUT.getNumber(), done.status.getCode());
}
 
Example 8
Source File: CallCredentialsApplyingTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void parameterPropagation_base() {
  Attributes transportAttrs = Attributes.newBuilder().set(ATTR_KEY, ATTR_VALUE).build();
  when(mockTransport.getAttributes()).thenReturn(transportAttrs);

  transport.newStream(method, origHeaders, callOptions);

  ArgumentCaptor<Attributes> attrsCaptor = ArgumentCaptor.forClass(null);
  verify(mockCreds).applyRequestMetadata(same(method), attrsCaptor.capture(), same(mockExecutor),
      any(CallCredentials.MetadataApplier.class));
  Attributes attrs = attrsCaptor.getValue();
  assertSame(ATTR_VALUE, attrs.get(ATTR_KEY));
  assertSame(AUTHORITY, attrs.get(CallCredentials.ATTR_AUTHORITY));
  assertSame(SecurityLevel.NONE, attrs.get(CallCredentials.ATTR_SECURITY_LEVEL));
}
 
Example 9
Source File: OnBoardingControllerTest.java    From staffjoy with MIT License 5 votes vote down vote up
@Test
public void testOnboardingWorker() {
    // arrage mock
    String userId = UUID.randomUUID().toString();
    AccountDto accountDto = AccountDto.builder()
            .name("test_user001")
            .phoneNumber("11111111111")
            .email("[email protected]")
            .id(userId)
            .memberSince(Instant.now().minus(30, ChronoUnit.DAYS))
            .confirmedAndActive(true)
            .photoUrl("https://staffjoy.xyz/photo/test01.png")
            .build();
    when(accountClient.getAccount(AuthConstant.AUTHORIZATION_BOT_SERVICE, userId))
            .thenReturn(new GenericAccountResponse(accountDto));

    String companyId = UUID.randomUUID().toString();
    CompanyDto companyDto = CompanyDto.builder()
            .name("test_company001")
            .defaultTimezone(TimeZone.getDefault().getID())
            .defaultDayWeekStarts("Monday")
            .id(companyId)
            .build();
    when(companyClient.getCompany(AuthConstant.AUTHORIZATION_BOT_SERVICE, companyId))
            .thenReturn(new GenericCompanyResponse(companyDto));

    when(mailClient.send(any(EmailRequest.class))).thenReturn(BaseResponse.builder().message("mail sent").build());

    BaseResponse baseResponse = botClient.onboardWorker(OnboardWorkerRequest.builder().companyId(companyId).userId(userId).build());
    log.info(baseResponse.toString());
    assertThat(baseResponse.isSuccess()).isTrue();
    ArgumentCaptor<EmailRequest> argument = ArgumentCaptor.forClass(EmailRequest.class);
    verify(mailClient, times(1)).send(argument.capture());
    EmailRequest emailRequest = argument.getValue();
    log.info(emailRequest.toString());
    assertThat(emailRequest.getTo()).isEqualTo(accountDto.getEmail());
    assertThat(emailRequest.getName()).isEqualTo(accountDto.getName());
    assertThat(emailRequest.getSubject()).isEqualTo("Onboarding Message");
    assertThat(emailRequest.getHtmlBody()).contains(userId, accountDto.getName(), companyDto.getName());
}
 
Example 10
Source File: GraphQlClientFixture.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
MultivaluedMap<String, Object> sentHeaders() {
    @SuppressWarnings("unchecked")
    ArgumentCaptor<MultivaluedMap<String, Object>> captor = ArgumentCaptor.forClass(MultivaluedMap.class);
    BDDMockito.then(mockInvocationBuilder).should().headers(captor.capture());
    MultivaluedMap<String, Object> map = captor.getValue();
    return (map == null) ? new MultivaluedHashMap<>() : map;
}
 
Example 11
Source File: TestHeartbeatEndpointTask.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testheartbeatWithAllReports() throws Exception {
  OzoneConfiguration conf = new OzoneConfiguration();
  StateContext context = new StateContext(conf, DatanodeStates.RUNNING,
      Mockito.mock(DatanodeStateMachine.class));

  StorageContainerDatanodeProtocolClientSideTranslatorPB scm =
      Mockito.mock(
          StorageContainerDatanodeProtocolClientSideTranslatorPB.class);
  ArgumentCaptor<SCMHeartbeatRequestProto> argument = ArgumentCaptor
      .forClass(SCMHeartbeatRequestProto.class);
  Mockito.when(scm.sendHeartbeat(argument.capture()))
      .thenAnswer(invocation ->
          SCMHeartbeatResponseProto.newBuilder()
              .setDatanodeUUID(
                  ((SCMHeartbeatRequestProto)invocation.getArgument(0))
                      .getDatanodeDetails().getUuid())
              .build());

  HeartbeatEndpointTask endpointTask = getHeartbeatEndpointTask(
      conf, context, scm);
  context.addEndpoint(TEST_SCM_ENDPOINT);
  context.addReport(NodeReportProto.getDefaultInstance());
  context.addReport(ContainerReportsProto.getDefaultInstance());
  context.addReport(CommandStatusReportsProto.getDefaultInstance());
  context.addContainerAction(getContainerAction());
  endpointTask.call();
  SCMHeartbeatRequestProto heartbeat = argument.getValue();
  Assert.assertTrue(heartbeat.hasDatanodeDetails());
  Assert.assertTrue(heartbeat.hasNodeReport());
  Assert.assertTrue(heartbeat.hasContainerReport());
  Assert.assertTrue(heartbeat.getCommandStatusReportsCount() != 0);
  Assert.assertTrue(heartbeat.hasContainerActions());
}
 
Example 12
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 5 votes vote down vote up
@Test
public void writeDescriptor() {
    BluetoothGattCallback callback = connectAndGetCallback();
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    BluetoothGattService service = new BluetoothGattService(SERVICE_UUID, 0);
    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"),PROPERTY_INDICATE,0);
    BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.fromString("00002903-0000-1000-8000-00805f9b34fb"),0);
    service.addCharacteristic(characteristic);
    characteristic.addDescriptor(descriptor);

    when(gatt.getServices()).thenReturn(Arrays.asList(service));
    byte[] originalByteArray = new byte[]{0x01};
    peripheral.writeDescriptor(descriptor, originalByteArray);

    verify(gatt).writeDescriptor(descriptor);

    callback.onDescriptorWrite(gatt, descriptor, 0);

    ArgumentCaptor<BluetoothPeripheral> captorPeripheral = ArgumentCaptor.forClass(BluetoothPeripheral.class);
    ArgumentCaptor<byte[]> captorValue = ArgumentCaptor.forClass(byte[].class);
    ArgumentCaptor<BluetoothGattDescriptor> captorDescriptor = ArgumentCaptor.forClass(BluetoothGattDescriptor.class);
    ArgumentCaptor<Integer> captorStatus = ArgumentCaptor.forClass(Integer.class);
    verify(peripheralCallback).onDescriptorWrite(captorPeripheral.capture(), captorValue.capture(), captorDescriptor.capture(), captorStatus.capture());

    byte[] value = captorValue.getValue();
    assertEquals(0x01, value[0]);
    assertNotEquals(value, originalByteArray);   // Check if the byte array has been copied
    assertEquals(peripheral, captorPeripheral.getValue());
    assertEquals(descriptor, captorDescriptor.getValue());
    assertEquals(GATT_SUCCESS, (int) captorStatus.getValue() );
}
 
Example 13
Source File: SimpleBrokerMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 14
Source File: ChannelzServiceTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
private GetServersResponse getServersHelper(long startId) {
  @SuppressWarnings("unchecked")
  StreamObserver<GetServersResponse> observer = mock(StreamObserver.class);
  ArgumentCaptor<GetServersResponse> responseCaptor
      = ArgumentCaptor.forClass(GetServersResponse.class);
  service.getServers(
      GetServersRequest.newBuilder().setStartServerId(startId).build(),
      observer);
  verify(observer).onNext(responseCaptor.capture());
  verify(observer).onCompleted();
  return responseCaptor.getValue();
}
 
Example 15
Source File: GrandExchangePluginTest.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testCancelTrade()
{
	SavedOffer savedOffer = new SavedOffer();
	savedOffer.setItemId(ItemID.ABYSSAL_WHIP);
	savedOffer.setQuantitySold(1);
	savedOffer.setTotalQuantity(10);
	savedOffer.setPrice(1000);
	savedOffer.setSpent(25);
	savedOffer.setState(GrandExchangeOfferState.BUYING);
	when(configManager.getConfiguration("geoffer.adam", "0")).thenReturn(GSON.toJson(savedOffer));

	GrandExchangeOffer grandExchangeOffer = mock(GrandExchangeOffer.class);
	when(grandExchangeOffer.getQuantitySold()).thenReturn(1);
	when(grandExchangeOffer.getItemId()).thenReturn(ItemID.ABYSSAL_WHIP);
	when(grandExchangeOffer.getTotalQuantity()).thenReturn(10);
	when(grandExchangeOffer.getPrice()).thenReturn(1000);
	when(grandExchangeOffer.getSpent()).thenReturn(25);
	when(grandExchangeOffer.getState()).thenReturn(GrandExchangeOfferState.CANCELLED_BUY);
	grandExchangePlugin.submitTrade(0, grandExchangeOffer);

	ArgumentCaptor<GrandExchangeTrade> captor = ArgumentCaptor.forClass(GrandExchangeTrade.class);
	verify(grandExchangeClient).submit(captor.capture());

	GrandExchangeTrade trade = captor.getValue();
	assertTrue(trade.isBuy());
	assertTrue(trade.isCancel());
	assertEquals(ItemID.ABYSSAL_WHIP, trade.getItemId());
	assertEquals(1, trade.getQty());
	assertEquals(10, trade.getTotal());
	assertEquals(25, trade.getSpent());
}
 
Example 16
Source File: TestHeartbeatEndpointTask.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testheartbeatWithContainerReports() throws Exception {
  OzoneConfiguration conf = new OzoneConfiguration();
  StateContext context = new StateContext(conf, DatanodeStates.RUNNING,
      Mockito.mock(DatanodeStateMachine.class));

  StorageContainerDatanodeProtocolClientSideTranslatorPB scm =
      Mockito.mock(
          StorageContainerDatanodeProtocolClientSideTranslatorPB.class);
  ArgumentCaptor<SCMHeartbeatRequestProto> argument = ArgumentCaptor
      .forClass(SCMHeartbeatRequestProto.class);
  Mockito.when(scm.sendHeartbeat(argument.capture()))
      .thenAnswer(invocation ->
          SCMHeartbeatResponseProto.newBuilder()
              .setDatanodeUUID(
                  ((SCMHeartbeatRequestProto)invocation.getArgument(0))
                      .getDatanodeDetails().getUuid())
              .build());

  HeartbeatEndpointTask endpointTask = getHeartbeatEndpointTask(
      conf, context, scm);
  context.addEndpoint(TEST_SCM_ENDPOINT);
  context.addReport(ContainerReportsProto.getDefaultInstance());
  endpointTask.call();
  SCMHeartbeatRequestProto heartbeat = argument.getValue();
  Assert.assertTrue(heartbeat.hasDatanodeDetails());
  Assert.assertFalse(heartbeat.hasNodeReport());
  Assert.assertTrue(heartbeat.hasContainerReport());
  Assert.assertTrue(heartbeat.getCommandStatusReportsCount() == 0);
  Assert.assertFalse(heartbeat.hasContainerActions());
}
 
Example 17
Source File: InternalPublishServiceImplTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void test_reset_dup_flag() {

    final SubscriberWithIdentifiers sub1 = new SubscriberWithIdentifiers("sub1", 1, (byte) 0, null);
    final SubscriberWithIdentifiers sub2 = new SubscriberWithIdentifiers("sub2", 1, (byte) 0, null);

    when(topicTree.getSubscribers("topic")).thenReturn(ImmutableSet.of(sub1, sub2));

    final PUBLISH publish = TestMessageUtil.createMqtt5Publish("topic");
    publish.setDuplicateDelivery(true);

    publishService.publish(publish, executorService, "sub1");

    final ArgumentCaptor<PUBLISH> captor = ArgumentCaptor.forClass(PUBLISH.class);
    verify(publishDistributor, atLeastOnce()).distributeToNonSharedSubscribers(anyMap(), captor.capture(), any());

    final PUBLISH value = captor.getValue();

    assertFalse(value.isDuplicateDelivery());
}
 
Example 18
Source File: SyncStatusNodePermissioningProviderTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Before
public void before() {
  final ArgumentCaptor<InSyncListener> inSyncSubscriberCaptor =
      ArgumentCaptor.forClass(InSyncListener.class);
  final ArgumentCaptor<Long> syncToleranceCaptor = ArgumentCaptor.forClass(Long.class);
  when(synchronizer.subscribeInSync(
          inSyncSubscriberCaptor.capture(), syncToleranceCaptor.capture()))
      .thenReturn(1L);
  bootnodes.add(bootnode);

  @SuppressWarnings("unchecked")
  final ArgumentCaptor<IntSupplier> syncGaugeCallbackCaptor =
      ArgumentCaptor.forClass(IntSupplier.class);

  when(metricsSystem.createCounter(
          BesuMetricCategory.PERMISSIONING,
          "sync_status_node_check_count",
          "Number of times the sync status permissioning provider has been checked"))
      .thenReturn(checkCounter);
  when(metricsSystem.createCounter(
          BesuMetricCategory.PERMISSIONING,
          "sync_status_node_check_count_permitted",
          "Number of times the sync status permissioning provider has been checked and returned permitted"))
      .thenReturn(checkPermittedCounter);
  when(metricsSystem.createCounter(
          BesuMetricCategory.PERMISSIONING,
          "sync_status_node_check_count_unpermitted",
          "Number of times the sync status permissioning provider has been checked and returned unpermitted"))
      .thenReturn(checkUnpermittedCounter);
  this.provider = new SyncStatusNodePermissioningProvider(synchronizer, bootnodes, metricsSystem);
  this.inSyncListener = inSyncSubscriberCaptor.getValue();
  assertThat(syncToleranceCaptor.getValue()).isEqualTo(0);
  verify(metricsSystem)
      .createIntegerGauge(
          eq(BesuMetricCategory.PERMISSIONING),
          eq("sync_status_node_sync_reached"),
          eq("Whether the sync status permissioning provider has realised sync yet"),
          syncGaugeCallbackCaptor.capture());
  this.syncGauge = syncGaugeCallbackCaptor.getValue();

  verify(synchronizer).subscribeInSync(any(), eq(0L));
}
 
Example 19
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 4 votes vote down vote up
@Test
public void cancelConnectionTest() throws Exception {
    peripheral.connect();

    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

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

    verify(device).connectGatt(any(Context.class), anyBoolean(), captor.capture(), anyInt());

    BluetoothGattCallback callback = captor.getValue();
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    peripheral.cancelConnection();

    verify(gatt).disconnect();

    assertEquals(STATE_DISCONNECTING,  peripheral.getState());

    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_DISCONNECTED);

    verify(gatt).close();
}
 
Example 20
Source File: LiveDataTest.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private GenericLifecycleObserver getGenericLifecycleObserver(Lifecycle lifecycle) {
    ArgumentCaptor<GenericLifecycleObserver> captor =
            ArgumentCaptor.forClass(GenericLifecycleObserver.class);
    verify(lifecycle).addObserver(captor.capture());
    return (captor.getValue());
}