Java Code Examples for org.mockito.ArgumentMatchers

The following examples show how to use org.mockito.ArgumentMatchers. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cia   Source File: LogoutClickListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Show notification failure test.
 */
@Test
public void showNotificationFailureTest() {
	final LogoutRequest request = new LogoutRequest();		
	final LogoutClickListener listener = Mockito.spy(new LogoutClickListener(request));
	final ApplicationManager applicationManager = Mockito.mock(ApplicationManager.class);
	Mockito.doReturn(applicationManager).when(listener).getApplicationManager();
	
	final LogoutResponse response = new LogoutResponse(ServiceResult.FAILURE);
	response.setErrorMessage("errorMessage");
	Mockito.when(applicationManager.service(request)).thenReturn(response);
	
	Mockito.doNothing().when(listener).showNotification(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(Type.class));
	listener.buttonClick(new ClickEvent(new Panel()));
	Mockito.verify(listener).showNotification(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(Type.class));
}
 
Example 2
Source Project: POC   Source File: CustomerControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testUpdateCustomer() throws Exception {
	given(this.customerService.getCustomer(ArgumentMatchers.anyLong()))
			.willReturn(Customer.builder().firstName("firstName").build());

	final Customer updateRequest = this.customer;
	final LocalDateTime dateOfBirth = LocalDateTime.now();
	updateRequest.setDateOfBirth(dateOfBirth);
	given(this.customerService.updateCustomer(ArgumentMatchers.any(Customer.class), ArgumentMatchers.anyLong()))
			.willReturn(this.customer);

	this.mockMvc
			.perform(MockMvcRequestBuilders.put("/rest/customers/{customerId}", RandomUtils.nextLong())
					.content(this.objectMapper.writeValueAsString(updateRequest))
					.contentType(MediaType.APPLICATION_JSON))
			.andExpect(status().isOk()).andExpect(jsonPath("firstName").value("firstName"))
			.andExpect(jsonPath("lastName").value("lastName"))
			.andExpect(jsonPath("dateOfBirth").value(dateOfBirth.toString()));
}
 
Example 3
private Map<String, DataSource> getDataSourceMap() throws SQLException {
    DataSource dataSource = mock(DataSource.class);
    Connection connection = mock(Connection.class);
    DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class);
    Statement statement = mock(Statement.class);
    ResultSet resultSet = mock(ResultSet.class);
    when(statement.getResultSet()).thenReturn(resultSet);
    when(resultSet.next()).thenReturn(false);
    when(dataSource.getConnection()).thenReturn(connection);
    when(connection.getMetaData()).thenReturn(databaseMetaData);
    when(connection.createStatement()).thenReturn(statement);
    when(statement.executeQuery(Mockito.anyString())).thenReturn(resultSet);
    when(statement.getConnection()).thenReturn(connection);
    when(statement.getConnection().getMetaData().getTables(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(resultSet);
    when(resultSet.next()).thenReturn(false);
    when(statement.getConnection().getMetaData().getURL()).thenReturn("jdbc:h2:mem:demo_ds;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    when(statement.getConnection().getMetaData().getColumns(null, null, "table_0", "%")).thenReturn(mock(ResultSet.class));
    when(statement.getConnection().getMetaData().getPrimaryKeys(null, null, "table_0")).thenReturn(mock(ResultSet.class));
    when(statement.getConnection().getMetaData().getIndexInfo(null, null, "table_0", false, false)).thenReturn(mock(ResultSet.class));
    Map<String, DataSource> result = new HashMap<>(1);
    result.put("ds", dataSource);
    return result;
}
 
Example 4
Source Project: besu   Source File: GraphQLHttpServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void ethGetUncleCountByBlockNumber() throws Exception {
  final int uncleCount = 5;
  @SuppressWarnings("unchecked")
  final BlockWithMetadata<TransactionWithMetadata, Hash> block =
      Mockito.mock(BlockWithMetadata.class);
  @SuppressWarnings("unchecked")
  final List<Hash> list = Mockito.mock(List.class);
  Mockito.when(blockchainQueries.blockByNumber(ArgumentMatchers.anyLong()))
      .thenReturn(Optional.of(block));
  Mockito.when(block.getOmmers()).thenReturn(list);
  Mockito.when(list.size()).thenReturn(uncleCount);

  final String query = "{block(number:\"3\") {ommerCount}}";

  final RequestBody body = RequestBody.create(query, GRAPHQL);
  try (final Response resp = client.newCall(buildPostRequest(body)).execute()) {
    Assertions.assertThat(resp.code()).isEqualTo(200);
    final String jsonStr = resp.body().string();
    final JsonObject json = new JsonObject(jsonStr);
    testHelper.assertValidGraphQLResult(json);
    final int result = json.getJsonObject("data").getJsonObject("block").getInteger("ommerCount");
    Assertions.assertThat(result).isEqualTo(uncleCount);
  }
}
 
Example 5
Source Project: rubix   Source File: TestHeartbeatService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Verify that the validation success metrics are not registered when validation is disabled.
 *
 * @throws TTransportException if the BookKeeper client cannot be created.
 */
@Test
public void verifyValidationMetricsAreCorrectlyRegistered_validationDisabled() throws IOException, TTransportException
{
  CacheConfig.setValidationEnabled(conf, false);

  final BookKeeperFactory bookKeeperFactory = mock(BookKeeperFactory.class);
  when(bookKeeperFactory.createBookKeeperClient(anyString(), ArgumentMatchers.<Configuration>any())).thenReturn(
      new RetryingPooledBookkeeperClient(
          new Poolable<TTransport>(new TSocket("localhost", CacheConfig.getBookKeeperServerPort(conf), CacheConfig.getServerConnectTimeout(conf)), null, "localhost"),
          "localhost",
          conf));

  final MetricRegistry metrics = new MetricRegistry();

  // Disable default reporters for this BookKeeper, since they will conflict with the running server.
  CacheConfig.setMetricsReporters(conf, "");
  try (BookKeeperMetrics bookKeeperMetrics = new BookKeeperMetrics(conf, metrics)) {
    final BookKeeper bookKeeper = new CoordinatorBookKeeper(conf, bookKeeperMetrics);
    final HeartbeatService heartbeatService = new HeartbeatService(conf, metrics, bookKeeperFactory, bookKeeper);

    assertNull(metrics.getGauges().get(BookKeeperMetrics.ValidationMetric.CACHING_VALIDATION_SUCCESS_GAUGE.getMetricName()), "Caching validation success metric should not be registered!");
    assertNull(metrics.getGauges().get(BookKeeperMetrics.ValidationMetric.FILE_VALIDATION_SUCCESS_GAUGE.getMetricName()), "File validation success metric should not be registered!");
  }
}
 
Example 6
@Test
public void testExecute_shouldFailForBadProject_reachableErrors() throws RepositoryException {
  try {
    // This pair of artifacts contains linkage errors on grpc-core's use of Verify. Because
    // grpc-core is included in entry point jars, the errors are reachable.
    setupMockDependencyResolution(
        "com.google.api-client:google-api-client:1.27.0", "io.grpc:grpc-core:1.17.1");
    rule.setReportOnlyReachable(true);
    rule.execute(mockRuleHelper);
    Assert.fail(
        "The rule should raise an EnforcerRuleException for artifacts with reachable errors");
  } catch (EnforcerRuleException ex) {
    // pass
    verify(mockLog)
        .error(ArgumentMatchers.startsWith("Linkage Checker rule found 1 reachable error."));
    assertEquals(
        "Failed while checking class path. See above error report.", ex.getMessage());
  }
}
 
Example 7
@Test(expected = UserCreationException.class)
public void executeRethrowsTheExceptionsOfTheLocalUserCreator() throws Exception {
  doThrow(new UserCreationException("")).when(localUserCreator).create(ArgumentMatchers.any());
  ImmutableMultimap<String, String> immutableMultimap = ImmutableMultimap.<String, String>builder()
    .put(UserInfoKeys.USER_PID, PID)
    .put(UserInfoKeys.USER_NAME, USER_NAME)
    .put(UserInfoKeys.PASSWORD, PWD)
    .put(UserInfoKeys.GIVEN_NAME, GIVEN_NAME)
    .put(UserInfoKeys.SURNAME, SURNAME)
    .put(UserInfoKeys.EMAIL_ADDRESS, EMAIL)
    .put(UserInfoKeys.ORGANIZATION, ORGANIZATION)
    .put(UserInfoKeys.VRE_ID, VRE_ID)
    .put(UserInfoKeys.VRE_ROLE, VRE_ROLE)
    .build();

  instance.execute(immutableMultimap, mock(PrintWriter.class));
}
 
Example 8
Source Project: cia   Source File: SearchDocumentClickListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Show notification failure test.
 */
@Test
public void showNotificationFailureTest() {
	final SearchDocumentRequest request = new SearchDocumentRequest();		
	final SearchDocumentClickListener listener = Mockito.spy(new SearchDocumentClickListener(request,null));
	final ApplicationManager applicationManager = Mockito.mock(ApplicationManager.class);
	Mockito.doReturn(applicationManager).when(listener).getApplicationManager();
	
	final SearchDocumentResponse response = new SearchDocumentResponse(ServiceResult.FAILURE);
	response.setErrorMessage("errorMessage");
	Mockito.when(applicationManager.service(request)).thenReturn(response);
	
	Mockito.doNothing().when(listener).showNotification(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(Type.class));
	listener.buttonClick(new ClickEvent(new Panel()));
	Mockito.verify(listener).showNotification(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(Type.class));
}
 
Example 9
Source Project: WiFiAnalyzer   Source File: DataManagerTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testAddSeriesDataNewWiFiDetails() {
    // setup
    GraphViewWrapper graphViewWrapper = mock(GraphViewWrapper.class);
    WiFiDetail wiFiDetail = makeWiFiDetail("SSID", 2455);
    Set<WiFiDetail> wiFiDetails = Collections.singleton(wiFiDetail);
    when(graphViewWrapper.isNewSeries(wiFiDetail)).thenReturn(true);
    // execute
    fixture.addSeriesData(graphViewWrapper, wiFiDetails, GraphConstants.MAX_Y);
    // validate
    verify(graphViewWrapper).isNewSeries(wiFiDetail);
    verify(graphViewWrapper).addSeries(
        eq(wiFiDetail),
        ArgumentMatchers.<TitleLineGraphSeries<DataPoint>>any(),
        eq(Boolean.TRUE));
}
 
Example 10
Source Project: joal   Source File: BandwidthDispatcherNotifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"ResultOfMethodCallIgnored", "TypeMayBeWeakened"})
@Test
public void shouldRegisterAndUpdateOnStartSuccess() {
    final BandwidthDispatcher dispatcher = mock(BandwidthDispatcher.class);

    final BandwidthDispatcherNotifier notifier = new BandwidthDispatcherNotifier(dispatcher);

    final InfoHash infoHash = new InfoHash("qjfqjbqdui".getBytes());
    final Announcer announcer = mock(Announcer.class);
    doReturn(infoHash).when(announcer).getTorrentInfoHash();
    final SuccessAnnounceResponse successAnnounceResponse = mock(SuccessAnnounceResponse.class);
    doReturn(10).when(successAnnounceResponse).getLeechers();
    doReturn(15).when(successAnnounceResponse).getSeeders();
    notifier.onAnnounceStartSuccess(announcer, successAnnounceResponse);

    Mockito.verify(dispatcher, times(1)).registerTorrent(ArgumentMatchers.eq(infoHash));
    Mockito.verify(dispatcher, times(1)).updateTorrentPeers(ArgumentMatchers.eq(infoHash), ArgumentMatchers.eq(15), ArgumentMatchers.eq(10));
    Mockito.verifyNoMoreInteractions(dispatcher);
}
 
Example 11
@Test
public void testNodeAddressUpdate() {
    IeeeAddress ieeeAddress = new IeeeAddress("123456890ABCDEF");

    DeviceAnnounce announce = new DeviceAnnounce(12345, ieeeAddress, null);

    ZigBeeNetworkDiscoverer discoverer = new ZigBeeNetworkDiscoverer(networkManager);
    discoverer.setRetryPeriod(0);
    discoverer.setRequeryPeriod(0);
    discoverer.setRetryCount(0);

    discoverer.commandReceived(announce);
    Mockito.verify(networkManager, Mockito.times(1)).updateNode(ArgumentMatchers.any());

    ZigBeeEndpointAddress address = Mockito.mock(ZigBeeEndpointAddress.class);
    Mockito.when(address.getAddress()).thenReturn(12345);
    ZclCommand zclCommand = Mockito.mock(ZclCommand.class);
    Mockito.when(zclCommand.getSourceAddress()).thenReturn(address);
    discoverer.commandReceived(zclCommand);
}
 
Example 12
@Test
public void sendCommandBroadcast() throws Exception {
    System.out.println("--- " + Thread.currentThread().getStackTrace()[1].getMethodName());
    ZigBeeDongleEzsp dongle = new ZigBeeDongleEzsp(null);

    EzspProtocolHandler handler = Mockito.mock(EzspProtocolHandler.class);
    TestUtilities.setField(ZigBeeDongleEzsp.class, dongle, "frameHandler", handler);

    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    TestUtilities.setField(ZigBeeDongleEzsp.class, dongle, "executorService", executorService);

    ZigBeeApsFrame apsFrame = new ZigBeeApsFrame();
    apsFrame.setCluster(0);
    apsFrame.setProfile(ZigBeeProfileType.ZIGBEE_HOME_AUTOMATION.getKey());
    apsFrame.setAddressMode(ZigBeeNwkAddressMode.DEVICE);
    apsFrame.setDestinationAddress(0xfff9);
    apsFrame.setApsCounter(1);
    apsFrame.setRadius(30);
    apsFrame.setPayload(new int[] {});

    dongle.sendCommand(1, apsFrame);
    Mockito.verify(handler, Mockito.timeout(TIMEOUT).times(1))
            .sendEzspTransaction(ArgumentMatchers.any(EzspTransaction.class));
}
 
Example 13
@Test
public void assertWatch() {
    PostShardingCenterRepositoryEventListener postShardingCenterRepositoryEventListener = new PostShardingCenterRepositoryEventListener(centerRepository, Collections.singletonList("test")) {
        
        @Override
        protected ShardingOrchestrationEvent createShardingOrchestrationEvent(final DataChangedEvent event) {
            return mock(ShardingOrchestrationEvent.class);
        }
    };
    doAnswer(invocationOnMock -> {
        DataChangedEventListener listener = (DataChangedEventListener) invocationOnMock.getArguments()[1];
        listener.onChange(new DataChangedEvent("test", "value", DataChangedEvent.ChangedType.UPDATED));
        return mock(DataChangedEventListener.class);
    }).when(centerRepository).watch(anyString(), any(DataChangedEventListener.class));
    postShardingCenterRepositoryEventListener.watch(DataChangedEvent.ChangedType.UPDATED);
    verify(centerRepository).watch(eq("test"), ArgumentMatchers.any());
}
 
Example 14
Source Project: cymbal   Source File: ClusterProcessServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    List<String> clusterNodes = Lists.newArrayList(
            "adfa5a7fd3ae38358e0ebcb917cd397c3088f01f 192.168.1.1:[email protected] myself,master - 0 0 1 connected 0-5460",
            "e3837d23375f66994c3a72ed3198d4d3d738813e 192.168.1.1:838[email protected] slave 2e70ba28d9049459c38698b32029185979f9ecfb 0 1458128356219 2 connected",
            "2e70ba28d9049459c38698b32029185979f9ecfb 192.168.1.2:[email protected] master - 0 1458128353214 2 connected 5461-10922",
            "51be946e224265780f7bdb98a47f0b0d426e4122 192.168.1.2:[email protected] slave 9fc4a4bc97278a05464504fe0ee975b0f78d549b 0 1458128352213 3 connected",
            "8a5dac298cec6f37ee7bc996a393792156629023 192.168.1.3:[email protected] slave adfa5a7fd3ae38358e0ebcb917cd397c3088f01f 0 1458128354215 1 connected",
            "9fc4a4bc97278a05464504fe0ee975b0f78d549b 192.168.1.3:[email protected] master - 0 1458128355217 3 connected 10923-16383");
    Mockito.doReturn(Arrays.asList("OK", "OK")).when(redisShellUtilityService)
            .executeRedisShellScript(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any());
    Mockito.doReturn(Arrays.asList("OK", "OK")).when(redisShellUtilityService)
            .executeSentinelShellScript(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any());
    Mockito.doReturn(clusterNodes).when(redisShellUtilityService)
            .executeRedisShellScript(ArgumentMatchers.any(), ArgumentMatchers.eq(ShellCommand.REDIS_CLI_CMD),
                    ArgumentMatchers.any(), ArgumentMatchers.any(),
                    ArgumentMatchers.contains(RedisCommand.CLUSTER_NODES.getValue()),
                    ArgumentMatchers.eq(RedisReplyFormat.RAW.getValue()));
}
 
Example 15
Source Project: AwesomeValidation   Source File: ValidatorTest.java    License: MIT License 6 votes vote down vote up
private void mockCheckSomeCertainTypeField(String methodName, Boolean... returnValues) {
    try {
        ArrayList<Boolean> booleans = new ArrayList<>(Arrays.asList(returnValues));
        Boolean firstBoolean = booleans.remove(0);
        Boolean[] otherBooleans = booleans.toArray(new Boolean[booleans.size()]);
        // WORKAROUND: pass firstBoolean, otherBooleans instead of single returnValues
        // otherwise it would cause problem with varargs for doReturn(...)
        // org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
        // Boolean[] cannot be returned by checkXxxTypeField()
        // checkXxxTypeField() should return boolean
        Class<?> typeOfCallback = methodName.equals("checkCustomTypeField") ? CustomValidationCallback.class : ValidationCallback.class;
        PowerMockito.doReturn(firstBoolean, otherBooleans).when(mSpiedValidator, methodName, ArgumentMatchers.any(ValidationHolder.class), ArgumentMatchers.any(typeOfCallback));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source Project: byte-buddy   Source File: PluginEngineDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testImplicitFolderInput() throws Exception {
    File file = File.createTempFile("foo", "bar");
    assertThat(file.delete(), is(true));
    assertThat(file.mkdir(), is(true));
    Plugin.Engine engine = spy(new Plugin.Engine.Default());
    doAnswer(new Answer<Plugin.Engine.Summary>() {
        public Plugin.Engine.Summary answer(InvocationOnMock invocationOnMock) {
            if (!(invocationOnMock.getArgument(0) instanceof Plugin.Engine.Source.ForFolder)) {
                throw new AssertionError();
            } else if (!(invocationOnMock.getArgument(1) instanceof Plugin.Engine.Target.ForFolder)) {
                throw new AssertionError();
            }
            return null;
        }
    }).when(engine).apply(any(Plugin.Engine.Source.class), any(Plugin.Engine.Target.class), ArgumentMatchers.<Plugin.Factory>anyList());
    assertThat(engine.apply(file, file), nullValue(Plugin.Engine.Summary.class));
    assertThat(file.delete(), is(true));
}
 
Example 17
Source Project: spring-cloud-gcp   Source File: DatastoreTemplateTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void performTransactionTest() {

	DatastoreReaderWriter transactionContext = mock(DatastoreReaderWriter.class);

	when(this.datastore.runInTransaction(any())).thenAnswer((invocation) -> {
		TransactionCallable<String> callable = invocation.getArgument(0);
		return callable.run(transactionContext);
	});

	List<Entity> e1 = Collections
			.singletonList(this.e1);
	when(transactionContext.fetch(ArgumentMatchers.<Key[]>any())).thenReturn(e1);

	String finalResult = this.datastoreTemplate
			.performTransaction((datastoreOperations) -> {
				datastoreOperations.save(this.ob2);
				datastoreOperations.findById("ignored", TestEntity.class);
				return "all done";
			});

	assertThat(finalResult).isEqualTo("all done");
	verify(transactionContext, times(1)).put(ArgumentMatchers.<FullEntity[]>any());
	verify(transactionContext, times(2)).fetch((Key[]) any());
}
 
Example 18
@Test
public void test_simple_intercept() throws Exception {
    final ClientContextImpl clientContext =
            new ClientContextImpl(extensions, new ModifiableDefaultPermissionsImpl());

    final UnsubscribeInboundInterceptor interceptor =
            getIsolatedInboundInterceptor("SimpleUnsubscribeTestInterceptor");
    clientContext.addUnsubscribeInboundInterceptor(interceptor);

    channel.attr(ChannelAttributes.PLUGIN_CLIENT_CONTEXT).set(clientContext);
    channel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv3_1);

    when(extensions.getExtensionForClassloader(ArgumentMatchers.any(IsolatedPluginClassloader.class))).thenReturn(extension);

    channel.writeInbound(testUnsubscribe());
    UNSUBSCRIBE unsubscribe = channel.readInbound();
    while (unsubscribe == null) {
        channel.runPendingTasks();
        channel.runScheduledPendingTasks();
        unsubscribe = channel.readInbound();
    }
    Assert.assertNotNull(unsubscribe);
    Assert.assertTrue(isTriggered.get());
}
 
Example 19
Source Project: grpc-java   Source File: AltsHandshakerClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void startServerHandshakeWithPrefixBuffer() throws Exception {
  when(mockStub.send(ArgumentMatchers.<HandshakerReq>any()))
      .thenReturn(MockAltsHandshakerResp.getOkResponse(BYTES_CONSUMED));

  ByteBuffer inBytes = ByteBuffer.allocate(IN_BYTES_SIZE);
  inBytes.position(PREFIX_POSITION);
  ByteBuffer outFrame = handshaker.startServerHandshake(inBytes);

  assertEquals(ByteString.copyFrom(outFrame), MockAltsHandshakerResp.getOutFrame());
  assertFalse(handshaker.isFinished());
  assertNull(handshaker.getResult());
  assertNull(handshaker.getKey());
  assertEquals(PREFIX_POSITION + BYTES_CONSUMED, inBytes.position());
  assertEquals(IN_BYTES_SIZE - BYTES_CONSUMED - PREFIX_POSITION, inBytes.remaining());
}
 
Example 20
@Test
@DirtiesContext
public void testInvalidTaskName() {
	final String ERROR_MESSAGE =
			"Could not find task definition named " + TASK_NAME;
	VndErrors errors = new VndErrors("message", ERROR_MESSAGE, new Link("ref"));
	Mockito.doThrow(new DataFlowClientException(errors))
			.when(this.taskOperations)
			.launch(ArgumentMatchers.anyString(),
					ArgumentMatchers.any(),
					ArgumentMatchers.any(), ArgumentMatchers.any());
	TaskLauncherTasklet taskLauncherTasklet = getTaskExecutionTasklet();
	ChunkContext chunkContext = chunkContext();
	Throwable exception = assertThrows(DataFlowClientException.class,
			() -> taskLauncherTasklet.execute(null, chunkContext));
	Assertions.assertThat(exception.getMessage()).isEqualTo(ERROR_MESSAGE);
}
 
Example 21
Source Project: bazel   Source File: BinaryFormatFileTransportTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteWhenFileClosed() throws Exception {
  File output = tmp.newFile();
  BufferedOutputStream outputStream =
      new BufferedOutputStream(Files.newOutputStream(Paths.get(output.getAbsolutePath())));

  BuildEventStreamProtos.BuildEvent started =
      BuildEventStreamProtos.BuildEvent.newBuilder()
          .setStarted(BuildStarted.newBuilder().setCommand("build"))
          .build();
  when(buildEvent.asStreamProto(ArgumentMatchers.<BuildEventContext>any())).thenReturn(started);

  BinaryFormatFileTransport transport =
      new BinaryFormatFileTransport(
          outputStream,
          defaultOpts,
          new LocalFilesArtifactUploader(),
          artifactGroupNamer);

  transport.close().get();

  // This should not throw an exception.
  transport.sendBuildEvent(buildEvent);
  transport.close().get();

  // Also, nothing should have been written to the file
  try (InputStream in = new FileInputStream(output)) {
    assertThat(in.available()).isEqualTo(0);
  }
}
 
Example 22
Source Project: grpc-java   Source File: NettyClientHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void channelShutdownShouldFailInFlightStreams() throws Exception {
  createStream();

  handler().channelInactive(ctx());
  ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
  verify(streamListener).closed(captor.capture(), same(PROCESSED),
      ArgumentMatchers.<Metadata>notNull());
  assertEquals(Status.UNAVAILABLE.getCode(), captor.getValue().getCode());
}
 
Example 23
@Test
public void addCollectOutsideArticleSuccess() {
    login();
    FeedArticleData feedArticleData = new FeedArticleData();
    feedArticleData.setTitle("个人博客");
    feedArticleData.setAuthor("JsonChao");
    feedArticleData.setLink("www.github.io");
    feedArticleData.setCollect(false);
    mProjectListPresenter.addCollectOutsideArticle(0, feedArticleData);
    Mockito.verify(mView).showCollectOutsideArticle(ArgumentMatchers.eq(0),
            ArgumentMatchers.eq(feedArticleData),
            ArgumentMatchers.any(FeedArticleListData.class));
}
 
Example 24
Source Project: ehcache3   Source File: ConfigurationMergerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void jsr107LoaderGetsRegistered() {
  MutableConfiguration<Object, Object> configuration = new MutableConfiguration<>();
  CacheLoader<Object, Object> mock = mock(CacheLoader.class);
  RecordingFactory<CacheLoader<Object, Object>> factory = factoryOf(mock);
  configuration.setReadThrough(true).setCacheLoaderFactory(factory);

  merger.mergeConfigurations("cache", configuration);

  assertThat(factory.called, is(true));
  verify(cacheLoaderWriterFactory).registerJsr107Loader(eq("cache"), ArgumentMatchers.<CacheLoaderWriter<Object, Object>>isNotNull());
}
 
Example 25
@Test
public void HandleEphemeralDataRequestUninitialised() throws Exception {
    TestUtilities.outputTestHeader();
    ZclKeyEstablishmentCluster keCluster = Mockito.mock(ZclKeyEstablishmentCluster.class);
    IeeeAddress ieeeAddress = new IeeeAddress("1111111111111111");

    ZclKeyEstablishmentServer keServer = new ZclKeyEstablishmentServer(ieeeAddress, keCluster);

    ArgumentCaptor<ZclKeyEstablishmentCommand> commandArgumentCaptor = ArgumentCaptor
            .forClass(ZclKeyEstablishmentCommand.class);
    Mockito.when(keCluster.sendCommand(commandArgumentCaptor.capture())).thenReturn(null);

    ZigBeeCbkeExchange cbkeExchange = Mockito.mock(ZigBeeCbkeExchange.class);
    TestUtilities.setField(ZclKeyEstablishmentServer.class, keServer, "cbkeExchange", cbkeExchange);

    EphemeralDataRequestCommand command = new EphemeralDataRequestCommand(Mockito.mock(ByteArray.class));
    command.setCommandDirection(ZclCommandDirection.CLIENT_TO_SERVER);
    assertTrue(keServer.commandReceived(command));

    // State is not initialised
    Mockito.verify(keCluster, Mockito.timeout(TIMEOUT).times(1)).sendCommand(ArgumentMatchers.any());

    Mockito.verify(cbkeExchange, Mockito.timeout(TIMEOUT).times(1)).completeKeyExchange(false);

    // State gets reset back to UNINITIALISED after the FAILURE
    assertEquals(KeyEstablishmentState.UNINITIALISED,
            TestUtilities.getField(ZclKeyEstablishmentServer.class, keServer, "keyEstablishmentState"));

    // Verify the responses
    assertEquals(1, commandArgumentCaptor.getAllValues().size());

    TerminateKeyEstablishment terminateKeyEstablishment = (TerminateKeyEstablishment) commandArgumentCaptor
            .getAllValues().get(0);
    assertEquals(Integer.valueOf(KeyEstablishmentStatusEnum.BAD_MESSAGE.getKey()),
            terminateKeyEstablishment.getStatusCode());
    assertEquals(Integer.valueOf(1), terminateKeyEstablishment.getKeyEstablishmentSuite());
    assertEquals(Integer.valueOf(10), terminateKeyEstablishment.getWaitTime());
}
 
Example 26
public void testSendOnly(ZigBeeTransportProgressState state) {
    ZigBeeTransactionManager transactionManager = Mockito.mock(ZigBeeTransactionManager.class);
    ZigBeeCommand command = Mockito.mock(ZigBeeCommand.class);
    Mockito.when(command.getTransactionId()).thenReturn(12);

    ZigBeeTransactionFuture transactionFuture = new ZigBeeTransactionFuture();

    ZigBeeTransaction transaction = new ZigBeeTransaction(transactionManager, command, null);
    transaction.setTimerPeriod1(Integer.MAX_VALUE);
    transaction.setTimerPeriod2(Integer.MAX_VALUE);
    transaction.setFuture(transactionFuture);

    assertEquals(command, transaction.startTransaction());
    Mockito.verify(transactionManager, Mockito.times(1)).scheduleTask(ArgumentMatchers.any(Runnable.class),
            ArgumentMatchers.anyLong());

    // Wrong TID so gets ignored
    transaction.transactionStatusReceived(ZigBeeTransportProgressState.TX_NAK, 123);
    assertFalse(transactionFuture.isDone());
    assertFalse(transactionFuture.isCancelled());

    // Correct TID
    transaction.transactionStatusReceived(state, 12);

    Mockito.verify(transactionManager, Mockito.times(1)).transactionComplete(transaction,
            TransactionState.COMPLETE);

    assertTrue(transactionFuture.isDone());
    assertFalse(transactionFuture.isCancelled());
}
 
Example 27
Source Project: grpc-java   Source File: HeaderClientInterceptorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void clientHeaderDeliveredToServer() throws Exception {
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();
  // Create a server, add service, start, and register for automatic graceful shutdown.
  grpcCleanup.register(InProcessServerBuilder.forName(serverName).directExecutor()
      .addService(ServerInterceptors.intercept(new GreeterImplBase() {}, mockServerInterceptor))
      .build().start());
  // Create a client channel and register for automatic graceful shutdown.
  ManagedChannel channel = grpcCleanup.register(
      InProcessChannelBuilder.forName(serverName).directExecutor().build());
  GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(
      ClientInterceptors.intercept(channel, new HeaderClientInterceptor()));
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);

  try {
    blockingStub.sayHello(HelloRequest.getDefaultInstance());
    fail();
  } catch (StatusRuntimeException expected) {
    // expected because the method is not implemented at server side
  }

  verify(mockServerInterceptor).interceptCall(
      ArgumentMatchers.<ServerCall<HelloRequest, HelloReply>>any(),
      metadataCaptor.capture(),
      ArgumentMatchers.<ServerCallHandler<HelloRequest, HelloReply>>any());
  assertEquals(
      "customRequestValue",
      metadataCaptor.getValue().get(HeaderClientInterceptor.CUSTOM_HEADER_KEY));
}
 
Example 28
@Ignore("connecting to the outside world makes this test flaky")
@Test(expected = SSLHandshakeException.class)
public void testCommonClientUsesExtensibleTrustManagerFailure() throws Throwable {
    doThrow(new CertificateException()).when(extensibleTrustManager).checkServerTrusted(
            ArgumentMatchers.any(X509Certificate[].class), anyString(), ArgumentMatchers.any(SSLEngine.class));
    HttpClient httpClient = webClientFactory.getCommonHttpClient();

    try {
        httpClient.GET(TEST_URL);
    } catch (ExecutionException e) {
        throw e.getCause();
    }
}
 
Example 29
@Test
public void assertFailoverIfUnnecessaryWhenItemsRootNodeIsEmpty() {
    when(jobNodeStorage.isJobNodeExisted("leader/failover/items")).thenReturn(true);
    when(jobNodeStorage.getJobNodeChildrenKeys("leader/failover/items")).thenReturn(Collections.emptyList());
    failoverService.failoverIfNecessary();
    verify(jobNodeStorage).isJobNodeExisted("leader/failover/items");
    verify(jobNodeStorage).getJobNodeChildrenKeys("leader/failover/items");
    verify(jobNodeStorage, times(0)).executeInLeader(eq("leader/failover/latch"), ArgumentMatchers.<FailoverService.FailoverLeaderExecutionCallback>any());
}
 
Example 30
@Test
public void scheduleTask() throws Exception {
    TestUtilities.outputTestHeader();
    ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager();
    ScheduledExecutorService scheduler = Mockito.mock(ScheduledExecutorService.class);
    TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "executorService", scheduler);

    assertNull(networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 0));
    assertNull(networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 1));
    assertNull(networkManager.scheduleTask(Mockito.mock(Runnable.class), 0));
    networkManager.executeTask(Mockito.mock(Runnable.class));
    assertNull(networkManager.rescheduleTask(Mockito.mock(ScheduledFuture.class), Mockito.mock(Runnable.class), 0));

    TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "networkState", ZigBeeNetworkState.ONLINE);

    networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 0);
    Mockito.verify(scheduler, Mockito.times(2)).schedule(ArgumentMatchers.any(Runnable.class),
            ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));

    networkManager.scheduleTask(Mockito.mock(Runnable.class), 0, 1);
    Mockito.verify(scheduler, Mockito.times(2)).scheduleAtFixedRate(ArgumentMatchers.any(Runnable.class),
            ArgumentMatchers.anyLong(), ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));

    networkManager.scheduleTask(Mockito.mock(Runnable.class), 0);
    Mockito.verify(scheduler, Mockito.times(3)).schedule(ArgumentMatchers.any(Runnable.class),
            ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));

    networkManager.executeTask(Mockito.mock(Runnable.class));
    Mockito.verify(scheduler, Mockito.times(1)).execute(ArgumentMatchers.any(Runnable.class));

    networkManager.rescheduleTask(Mockito.mock(ScheduledFuture.class), Mockito.mock(Runnable.class), 0);
    Mockito.verify(scheduler, Mockito.times(4)).schedule(ArgumentMatchers.any(Runnable.class),
            ArgumentMatchers.anyLong(), ArgumentMatchers.any(TimeUnit.class));
}