org.mockito.ArgumentMatchers Java Examples
The following examples show how to use
org.mockito.ArgumentMatchers.
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: TaskLauncherTaskletTests.java From spring-cloud-dataflow with Apache License 2.0 | 6 votes |
@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 #2
Source File: BandwidthDispatcherNotifierTest.java From joal with Apache License 2.0 | 6 votes |
@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 #3
Source File: ZigBeeNetworkDiscovererTest.java From com.zsmartsystems.zigbee with Eclipse Public License 1.0 | 6 votes |
@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 #4
Source File: LinkageCheckerRuleTest.java From cloud-opensource-java with Apache License 2.0 | 6 votes |
@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 #5
Source File: TestHeartbeatService.java From rubix with Apache License 2.0 | 6 votes |
/** * 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
Source File: GraphQLHttpServiceTest.java From besu with Apache License 2.0 | 6 votes |
@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 #7
Source File: DataManagerTest.java From WiFiAnalyzer with GNU General Public License v3.0 | 6 votes |
@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 #8
Source File: ZigBeeDongleEzspTest.java From com.zsmartsystems.zigbee with Eclipse Public License 1.0 | 6 votes |
@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 #9
Source File: ShardingSphereDataSourceFactoryTest.java From shardingsphere with Apache License 2.0 | 6 votes |
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 #10
Source File: PostShardingCenterRepositoryEventListenerTest.java From shardingsphere with Apache License 2.0 | 6 votes |
@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 #11
Source File: SearchDocumentClickListenerTest.java From cia with Apache License 2.0 | 6 votes |
/** * 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 #12
Source File: ClusterProcessServiceTest.java From cymbal with Apache License 2.0 | 6 votes |
@Before public void setup() { List<String> clusterNodes = Lists.newArrayList( "adfa5a7fd3ae38358e0ebcb917cd397c3088f01f 192.168.1.1:8381@17000 myself,master - 0 0 1 connected 0-5460", "e3837d23375f66994c3a72ed3198d4d3d738813e 192.168.1.1:8382@17004 slave 2e70ba28d9049459c38698b32029185979f9ecfb 0 1458128356219 2 connected", "2e70ba28d9049459c38698b32029185979f9ecfb 192.168.1.2:8381@17001 master - 0 1458128353214 2 connected 5461-10922", "51be946e224265780f7bdb98a47f0b0d426e4122 192.168.1.2:8382@17005 slave 9fc4a4bc97278a05464504fe0ee975b0f78d549b 0 1458128352213 3 connected", "8a5dac298cec6f37ee7bc996a393792156629023 192.168.1.3:8381@17003 slave adfa5a7fd3ae38358e0ebcb917cd397c3088f01f 0 1458128354215 1 connected", "9fc4a4bc97278a05464504fe0ee975b0f78d549b 192.168.1.3:8382@17002 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 #13
Source File: ValidatorTest.java From AwesomeValidation with MIT License | 6 votes |
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 #14
Source File: PluginEngineDefaultTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@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 #15
Source File: CustomerControllerTest.java From POC with Apache License 2.0 | 6 votes |
@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 #16
Source File: DatastoreTemplateTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@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 #17
Source File: UnsubscribeInboundInterceptorHandlerTest.java From hivemq-community-edition with Apache License 2.0 | 6 votes |
@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 #18
Source File: LogoutClickListenerTest.java From cia with Apache License 2.0 | 6 votes |
/** * 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 #19
Source File: UserCreationTaskTest.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
@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 #20
Source File: AltsHandshakerClientTest.java From grpc-java with Apache License 2.0 | 6 votes |
@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 #21
Source File: PageSettingsActionAspectTest.java From entando-components with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void executeUpdateSystemParams_4() throws Exception { String path = System.getProperty("java.io.tmpdir") + File.separator + "meta-inf" + File.separator + "robot.txt"; this.request.setParameter(PageSettingsActionAspect.PARAM_ROBOT_ALTERNATIVE_PATH_CODE, path); this.request.setParameter(PageSettingsActionAspect.PARAM_ROBOT_CONTENT_CODE, "Robot content"); when(configManager.getConfigItem(ArgumentMatchers.anyString())).thenReturn(CONFIG_PARAMETER); actionAspect.executeUpdateSystemParams(joinPoint); Mockito.verify(storageManager, Mockito.times(0)).saveFile(Mockito.anyString(), Mockito.anyBoolean(), Mockito.any(InputStream.class)); Mockito.verify(storageManager, Mockito.times(0)).deleteFile(Mockito.anyString(), Mockito.anyBoolean()); Assert.assertTrue(pageSettingsAction.hasFieldErrors()); Assert.assertEquals(1, pageSettingsAction.getFieldErrors().get(PageSettingsActionAspect.PARAM_ROBOT_ALTERNATIVE_PATH_CODE).size()); Mockito.verify(configManager, Mockito.times(1)).updateConfigItem(ArgumentMatchers.anyString(), ArgumentMatchers.anyString()); }
Example #22
Source File: ShardingAutoTableRuleConfigurationYamlSwapperTest.java From shardingsphere with Apache License 2.0 | 5 votes |
@Before public void setUp() throws ReflectiveOperationException { setSwapper("shardingStrategyYamlSwapper", shardingStrategyYamlSwapper); when(shardingStrategyYamlSwapper.swapToYamlConfiguration(ArgumentMatchers.any())).thenReturn(mock(YamlShardingStrategyConfiguration.class)); setSwapper("keyGenerateStrategyYamlSwapper", keyGenerateStrategyYamlSwapper); when(keyGenerateStrategyYamlSwapper.swapToYamlConfiguration(ArgumentMatchers.any())).thenReturn(mock(YamlKeyGenerateStrategyConfiguration.class)); }
Example #23
Source File: SegmentOutputStreamTest.java From pravega with Apache License 2.0 | 5 votes |
private void answerSuccess(ClientConnection connection) { doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { CompletedCallback callback = (CompletedCallback) invocation.getArgument(1); callback.complete(null); return null; } }).when(connection).sendAsync(ArgumentMatchers.<List<Append>>any(), Mockito.any(CompletedCallback.class)); }
Example #24
Source File: BinaryFormatFileTransportTest.java From bazel with Apache License 2.0 | 5 votes |
@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 #25
Source File: SimpleEmailServiceMailSenderTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test void testSendMultipleMails() throws Exception { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender( emailService); ArgumentCaptor<SendEmailRequest> request = ArgumentCaptor .forClass(SendEmailRequest.class); when(emailService.sendEmail(request.capture())) .thenReturn(new SendEmailResult().withMessageId("123")); mailSender.send(createSimpleMailMessage(), createSimpleMailMessage()); verify(emailService, times(2)) .sendEmail(ArgumentMatchers.any(SendEmailRequest.class)); }
Example #26
Source File: PipelineConfigTest.java From gocd with Apache License 2.0 | 5 votes |
@Test public void shouldNotEncryptSecurePropertiesInStagesIfPipelineHasATemplate() { PipelineConfig pipelineConfig = new PipelineConfig(); pipelineConfig.setTemplateName(new CaseInsensitiveString("some-template")); StageConfig mockStageConfig = mock(StageConfig.class); pipelineConfig.addStageWithoutValidityAssertion(mockStageConfig); pipelineConfig.encryptSecureProperties(new BasicCruiseConfig(), pipelineConfig); verify(mockStageConfig, never()).encryptSecureProperties(eq(new BasicCruiseConfig()), eq(pipelineConfig), ArgumentMatchers.any(StageConfig.class)); }
Example #27
Source File: ZigBeeNetworkManagerTest.java From com.zsmartsystems.zigbee with Eclipse Public License 1.0 | 5 votes |
@Test public void testPermitJoin() throws Exception { TestUtilities.outputTestHeader(); ZigBeeNetworkManager networkManager = mockZigBeeNetworkManager(); ZigBeeTransactionManager transactionManager = Mockito.mock(ZigBeeTransactionManager.class); TestUtilities.setField(ZigBeeNetworkManager.class, networkManager, "transactionManager", transactionManager); assertEquals(ZigBeeStatus.SUCCESS, networkManager.permitJoin(0)); Mockito.verify(transactionManager, Mockito.timeout(TIMEOUT).times(2)) .sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class)); assertEquals(ZigBeeStatus.SUCCESS, networkManager.permitJoin(254)); Mockito.verify(transactionManager, Mockito.timeout(TIMEOUT).times(4)) .sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class)); assertEquals(ZigBeeStatus.INVALID_ARGUMENTS, networkManager.permitJoin(255)); Mockito.verify(transactionManager, Mockito.timeout(TIMEOUT).times(4)) .sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class)); // Check that the unicast sends 1 frame networkManager.permitJoin(new ZigBeeEndpointAddress(1), 1); Mockito.verify(transactionManager, Mockito.timeout(TIMEOUT).times(5)) .sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class)); // Check that the broadcast sends 2 frames networkManager.permitJoin(1); Mockito.verify(transactionManager, Mockito.timeout(TIMEOUT).times(7)) .sendTransaction(ArgumentMatchers.any(ZigBeeCommand.class)); }
Example #28
Source File: SpecServiceTest.java From feast with Apache License 2.0 | 5 votes |
@Test public void shouldDoNothingIfNoChange() throws InvalidProtocolBufferException { when(storeRepository.findById("SERVING")).thenReturn(Optional.of(stores.get(0))); UpdateStoreResponse actual = specService.updateStore( UpdateStoreRequest.newBuilder().setStore(stores.get(0).toProto()).build()); UpdateStoreResponse expected = UpdateStoreResponse.newBuilder() .setStore(stores.get(0).toProto()) .setStatus(UpdateStoreResponse.Status.NO_CHANGE) .build(); verify(storeRepository, times(0)).save(ArgumentMatchers.any()); assertThat(actual, equalTo(expected)); }
Example #29
Source File: HeatTemplateBuilderTest.java From cloudbreak with Apache License 2.0 | 5 votes |
@Test public void buildTestWithExistingNetworkAndExistingSubnetAndAssignFloatingIpWithExistingSecurityGroups() { assumeTrue("Template doesn't support this feature, required version is '2.x' at least", isTemplateMajorVersionGreaterOrEqualThan()); //GIVEN NeutronNetworkView neutronNetworkView = createNeutronNetworkView("floating_pool_id"); Group group = groups.get(0); groups.clear(); String cloudSecurityId = "sec-group-id"; Security security = new Security(emptyList(), singletonList(cloudSecurityId)); Group groupWithSecGroup = new Group(group.getName(), InstanceGroupType.CORE, group.getInstances(), security, null, group.getInstanceAuthentication(), group.getInstanceAuthentication().getLoginUserName(), group.getInstanceAuthentication().getPublicKey(), 50, Optional.empty()); groups.add(groupWithSecGroup); //WHEN when(openStackUtil.adjustStackNameLength(ArgumentMatchers.anyString())).thenReturn("t"); ModelContext modelContext = new ModelContext(); modelContext.withExistingNetwork(true); modelContext.withExistingSubnet(true); modelContext.withGroups(groups); modelContext.withInstanceUserData(image); modelContext.withLocation(location()); modelContext.withStackName(stackName); modelContext.withNeutronNetworkView(neutronNetworkView); modelContext.withTemplateString(heatTemplateBuilder.getTemplate()); String templateString = heatTemplateBuilder.build(modelContext); //THEN assertThat(templateString, not(containsString("cb-sec-group_" + 't'))); assertThat(templateString, not(containsString("type: OS::Neutron::SecurityGroup"))); assertThat(templateString, containsString(cloudSecurityId)); assertThat(templateString, containsString("app_net_id")); assertThat(templateString, not(containsString("app_network"))); assertThat(templateString, containsString("subnet_id")); assertThat(templateString, not(containsString("app_subnet"))); assertThat(templateString, containsString("network_id")); assertThat(templateString, containsString("public_net_id")); }
Example #30
Source File: ResourceAttributeHandlerTest.java From entando-components with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void endAttribute_1() throws SAXException { handler.setIntoMetadatas(true); handler.setMetadataKey("key_1"); handler.setCurrentLangId("en"); StringBuffer buffer = new StringBuffer("value"); handler.endAttribute("metadata", buffer); Mockito.verify(currentAttr, Mockito.times(1)).setMetadata(ArgumentMatchers.eq("key_1"), ArgumentMatchers.eq("en"), ArgumentMatchers.eq("value")); Assert.assertNull(handler.getCurrentLangId()); Assert.assertNull(handler.getMetadataKey()); }