org.mockito.Mockito Java Examples
The following examples show how to use
org.mockito.Mockito.
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: LawnAndGardenDeviceMoreControllerTest.java From arcusandroid with Apache License 2.0 | 6 votes |
@Test public void subsystemLoads1ZoneNormally() throws Exception { Fixtures.loadModel(ONE_ZONE_DEVICE_JSON); devices = DeviceModelProvider.instance().getModels(ImmutableSet.of(ONE_ZONE_DEVICE_ADDRESS)); controller = new LawnAndGardenDeviceMoreController(source, devices, client()); source.set((SubsystemModel) Fixtures.loadModel(ONE_ZONE_SUBSYSTEM_JSON)); LawnAndGardenDeviceMoreController.Callback cb = Mockito.mock(LawnAndGardenDeviceMoreController.Callback.class); controller.setCallback(cb); Mockito.verify(cb, Mockito.times(1)).showDevices(showDevicesCaptor.capture()); List<LawnAndGardenControllerModel> models = showDevicesCaptor.getValue(); assertFalse(models.isEmpty()); assertEquals(1, models.size()); assertEquals(1, models.get(0).getZoneCount()); Mockito.verifyNoMoreInteractions(cb); }
Example #2
Source File: GeoEnabledConsistencyReceiverTest.java From mobile-messaging-sdk-android with Apache License 2.0 | 6 votes |
@Test public void test_shouldNotProduceSecurityExceptionWithoutPermission_whenGeoDeactivated() { // Given //noinspection WrongConstant Mockito.when(contextMock.getSystemService(Mockito.eq(Context.LOCATION_SERVICE))).thenThrow(new SecurityException()); Mockito.when(geoHelperMock.isLocationEnabled(contextMock)).thenReturn(false); PreferenceHelper.saveBoolean(context, MobileMessagingProperty.GEOFENCING_ACTIVATED, false); // When try { geoEnabledConsistencyReceiverWithMock.onReceive(contextMock, providersChangedIntent); } catch (Exception ex) { exception = ex; } // Then assertNull(exception); Mockito.verify(geoHelperMock, Mockito.never()).isLocationEnabled(context); Mockito.verify(locationManagerMock, Mockito.never()).isProviderEnabled(LocationManager.NETWORK_PROVIDER); }
Example #3
Source File: UserServiceUnitTest.java From tutorials with MIT License | 6 votes |
@Test void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() { // Given user = new User("jerry", 12); Mockito.reset(userRepository); when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true); // When try { userService.register(user); fail("Should give an error"); } catch(Exception ex) { assertEquals(ex.getMessage(), Errors.USER_NAME_DUPLICATE); } // Then verify(userRepository, never()).insert(user); }
Example #4
Source File: TestDeleteSQS.java From nifi with Apache License 2.0 | 6 votes |
@Test public void testDeleteException() { runner.setProperty(DeleteSQS.QUEUE_URL, "https://sqs.us-west-2.amazonaws.com/123456789012/test-queue-000000000"); final Map<String, String> ff1Attributes = new HashMap<>(); ff1Attributes.put("filename", "1.txt"); ff1Attributes.put("sqs.receipt.handle", "test-receipt-handle-1"); runner.enqueue("TestMessageBody1", ff1Attributes); Mockito.when(mockSQSClient.deleteMessageBatch(Mockito.any(DeleteMessageBatchRequest.class))) .thenThrow(new AmazonSQSException("TestFail")); runner.assertValid(); runner.run(1); ArgumentCaptor<DeleteMessageBatchRequest> captureDeleteRequest = ArgumentCaptor.forClass(DeleteMessageBatchRequest.class); Mockito.verify(mockSQSClient, Mockito.times(1)).deleteMessageBatch(captureDeleteRequest.capture()); runner.assertAllFlowFilesTransferred(DeleteSQS.REL_FAILURE, 1); }
Example #5
Source File: ZosmfAuthenticationProviderTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void noDomainInResponse() throws IOException { authConfigurationProperties.setZosmfServiceId(ZOSMF); final Application application = createApplication(zosmfInstance); when(discovery.getApplication(ZOSMF)).thenReturn(application); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.SET_COOKIE, COOKIE1); headers.add(HttpHeaders.SET_COOKIE, COOKIE2); when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.<Class<Object>>any())) .thenReturn(new ResponseEntity<>(getResponse(false), headers, HttpStatus.OK)); ZosmfService zosmfService = createZosmfService(); ZosmfAuthenticationProvider zosmfAuthenticationProvider = new ZosmfAuthenticationProvider(authenticationService, zosmfService); Exception exception = assertThrows(AuthenticationServiceException.class, () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication), "Expected exception is not AuthenticationServiceException"); assertEquals("z/OSMF domain cannot be read.", exception.getMessage()); }
Example #6
Source File: ContextURLBuilderTest.java From olingo-odata4 with Apache License 2.0 | 6 votes |
@Test public void buildProperty() { EdmEntitySet entitySet = Mockito.mock(EdmEntitySet.class); Mockito.when(entitySet.getName()).thenReturn("Customers"); ContextURL contextURL = ContextURL.with().serviceRoot(serviceRoot) .entitySet(entitySet) .keyPath("1") .navOrPropertyPath("Name") .build(); assertEquals(serviceRoot + "$metadata#Customers(1)/Name", ContextURLBuilder.create(contextURL).toASCIIString()); contextURL = ContextURL.with().serviceRoot(serviceRoot) .entitySet(entitySet) .keyPath("one=1,two='two'") .navOrPropertyPath("ComplexName") .selectList("Part1") .build(); assertEquals(serviceRoot + "$metadata#Customers(one=1,two='two')/ComplexName(Part1)", ContextURLBuilder.create(contextURL).toASCIIString()); }
Example #7
Source File: TestVersionedFlowsResult.java From nifi with Apache License 2.0 | 6 votes |
@Test public void testReferenceResolver() { final VersionedFlowsResult result = new VersionedFlowsResult(ResultType.SIMPLE, flows); final ReferenceResolver resolver = result.createReferenceResolver(Mockito.mock(Context.class)); // should default to flow id when no option is specified Assert.assertEquals("ea752054-22c6-4fc0-b851-967d9a3837cb", resolver.resolve(null, 1).getResolvedValue()); Assert.assertEquals("ddf5f289-7502-46df-9798-4b0457c1816b", resolver.resolve(null, 2).getResolvedValue()); // should use flow id when flow id is specified Assert.assertEquals("ea752054-22c6-4fc0-b851-967d9a3837cb", resolver.resolve(CommandOption.FLOW_ID, 1).getResolvedValue()); Assert.assertEquals("ddf5f289-7502-46df-9798-4b0457c1816b", resolver.resolve(CommandOption.FLOW_ID, 2).getResolvedValue()); // should resolve the bucket id when bucket id option is used Assert.assertEquals("b1", resolver.resolve(CommandOption.BUCKET_ID, 1).getResolvedValue()); Assert.assertEquals("b2", resolver.resolve(CommandOption.BUCKET_ID, 2).getResolvedValue()); // should resolve to null when position doesn't exist Assert.assertEquals(null, resolver.resolve(CommandOption.FLOW_ID, 3)); }
Example #8
Source File: TemplateUtilsTest.java From aws-mock with MIT License | 6 votes |
@Test(expected = AwsMockException.class) public void Test_getProcessTemplateExceptionWithNoData() throws Exception { Configuration config = Mockito.mock(Configuration.class); Template template = Mockito.mock(Template.class); Whitebox.setInternalState(TemplateUtils.class, "conf", config); Mockito.doNothing().when(config) .setClassForTemplateLoading(Mockito.eq(TemplateUtils.class), Mockito.anyString()); Mockito.when(config.getTemplate(Mockito.anyString())).thenReturn(template); Mockito.doThrow(new TemplateException("Forced TemplateException", null)).when(template) .process(Mockito.any(), Mockito.any(Writer.class)); TemplateUtils.get(errFTemplateFile, null); }
Example #9
Source File: TestFailoverController.java From hadoop with Apache License 2.0 | 6 votes |
@Test public void testFailoverFromFaultyServiceFencingFailure() throws Exception { DummyHAService svc1 = new DummyHAService(HAServiceState.ACTIVE, svc1Addr); Mockito.doThrow(new ServiceFailedException("Failed!")) .when(svc1.proxy).transitionToStandby(anyReqInfo()); DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr); svc1.fencer = svc2.fencer = setupFencer(AlwaysFailFencer.class.getName()); AlwaysFailFencer.fenceCalled = 0; try { doFailover(svc1, svc2, false, false); fail("Failed over even though fencing failed"); } catch (FailoverFailedException ffe) { // Expected } assertEquals(1, AlwaysFailFencer.fenceCalled); assertSame(svc1, AlwaysFailFencer.fencedSvc); assertEquals(HAServiceState.ACTIVE, svc1.state); assertEquals(HAServiceState.STANDBY, svc2.state); }
Example #10
Source File: UserServiceProviderPactTest.java From spring-microservice-sample with GNU General Public License v3.0 | 6 votes |
@Before public void before() { Mockito.when(this.userRepository.findAll()) .thenReturn(Arrays.asList( User.builder().id(1L).username("user").password("password").email("[email protected]").build(), User.builder().id(1L).username("admin").password("password").email("[email protected]").build() )); Mockito.when(this.userRepository.findByUsername("user")) .thenReturn( Optional.of(User.builder().id(1L).username("user").password("password").email("[email protected]").build()) ); Mockito.when(this.userRepository.findByUsername("noneExisting")).thenReturn(Optional.empty()); reset(); webAppContextSetup(this.webApplicationContext); }
Example #11
Source File: TestPipelineConfigurationValidator.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testUpgradeOK() { StageLibraryTask lib = MockStages.createStageLibrary(); PipelineConfiguration conf = MockStages.createPipelineConfigurationSourceProcessorTarget(); // tweak validator upgrader to require upgrading the pipeline PipelineConfigurationValidator validator = new PipelineConfigurationValidator(lib, buildInfo, "name", conf); validator = Mockito.spy(validator); PipelineConfigurationUpgrader upgrader = Mockito.spy(new PipelineConfigurationUpgrader(){}); int currentVersion = upgrader.getPipelineDefinition().getVersion(); StageDefinition pipelineDef = Mockito.spy(upgrader.getPipelineDefinition()); Mockito.when(pipelineDef.getVersion()).thenReturn(currentVersion + 1); Mockito.when(pipelineDef.getUpgrader()).thenReturn(new StageUpgrader() { @Override public List<Config> upgrade(String library, String stageName, String stageInstance, int fromVersion, int toVersion, List<Config> configs) throws StageException { return configs; } }); Mockito.when(upgrader.getPipelineDefinition()).thenReturn(pipelineDef); Mockito.when(validator.getUpgrader()).thenReturn(upgrader); Assert.assertFalse(validator.validate().getIssues().hasIssues()); Assert.assertEquals(currentVersion + 1, conf.getVersion());; }
Example #12
Source File: JobRestControllerTest.java From genie with Apache License 2.0 | 6 votes |
@Test void wontForwardV4JobKillRequestIfOnCorrectHost() throws IOException, GenieException, GenieCheckedException { this.jobsProperties.getForwarding().setEnabled(true); final String jobId = UUID.randomUUID().toString(); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(this.persistenceService.getJobStatus(jobId)).thenReturn(JobStatus.RUNNING); Mockito.when(this.persistenceService.isV4(jobId)).thenReturn(true); Mockito.when(this.agentRoutingService.getHostnameForAgentConnection(jobId)) .thenReturn(Optional.of(this.hostname)); this.controller.killJob(jobId, null, request, response); Mockito.verify(this.persistenceService, Mockito.times(1)).getJobStatus(jobId); Mockito.verify(this.persistenceService, Mockito.times(1)).isV4(jobId); Mockito.verify(this.persistenceService, Mockito.never()).getJobHost(jobId); Mockito.verify(this.agentRoutingService, Mockito.times(1)).getHostnameForAgentConnection(jobId); Mockito .verify(this.restTemplate, Mockito.never()) .execute(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.any()); }
Example #13
Source File: IPv6DeviceReadDataTest.java From xbee-java with Mozilla Public License 2.0 | 6 votes |
/** * Test method for {@link com.digi.xbee.api.IPv6Device#readIPDataPacket(Inet6Address, int))}. * * @throws Exception */ @Test public final void testReadIPDataPacketWithIPv6() throws Exception { // Setup the resources for the test. receivedIPv6Data = "Received message data"; // Call the method under test. IPMessage readMessage = Whitebox.invokeMethod(ipv6Device, "readIPDataPacket", sourceIPv6Address, 100); // Verify the result. assertThat("Message must not be null", readMessage, is(not(equalTo(null)))); assertThat("Message must not be null", readMessage, is(not(equalTo(null)))); assertThat("IPv6 address must not be null", readMessage.getIPv6Address(), is(not(equalTo(null)))); assertThat("IPv6 address must be '" + sourceIPv6Address + "' and not '" + readMessage.getIPv6Address() + "'", readMessage.getIPv6Address(), is(equalTo(sourceIPv6Address))); assertThat("Source port must be '" + sourcePort + "' and not '" + readMessage.getSourcePort(), readMessage.getSourcePort(), is(equalTo(sourcePort))); assertThat("Destination port must be '" + destPort + "' and not '" + readMessage.getSourcePort(), readMessage.getDestPort(), is(equalTo(destPort))); assertThat("Protocol port must be '" + protocol.getName() + "' and not '" + readMessage.getProtocol().getName(), readMessage.getProtocol(), is(equalTo(protocol))); assertThat("Received data must be '" + receivedIPv6Data + "' and not '" + readMessage.getDataString() + "'", readMessage.getDataString(), is(equalTo(receivedIPv6Data))); Mockito.verify(mockXBeePacketsQueue).getFirstIPv6DataPacketFrom(sourceIPv6Address, 100); }
Example #14
Source File: OpenTracingExecutionDecoratorTest.java From smallrye-graphql with Apache License 2.0 | 6 votes |
@Test public void testExecutionTracing() { ExecutionInput executionInput = ExecutionInput.newExecutionInput() .query("{}") .context(GraphQLContext.newContext()) .executionId(ExecutionId.from("1")) .build(); ExecutionResult executionResult = Mockito.mock(ExecutionResult.class); OpenTracingExecutionDecorator openTracingExecutionDecorator = new OpenTracingExecutionDecorator(); openTracingExecutionDecorator.before(executionInput); openTracingExecutionDecorator.after(executionInput, executionResult); assertEquals(1, MockTracerOpenTracingService.MOCK_TRACER.finishedSpans().size(), "One span should be finished"); MockSpan span = MockTracerOpenTracingService.MOCK_TRACER.finishedSpans().get(0); assertEquals("GraphQL", span.operationName()); assertEquals("1", span.tags().get("graphql.executionId"), "ExecutionId should be present in span"); }
Example #15
Source File: TestDiagnosticsManager.java From samza with Apache License 2.0 | 6 votes |
@Test public void testDiagnosticsManagerStart() { SystemProducer mockSystemProducer = Mockito.mock(SystemProducer.class); DiagnosticsManager diagnosticsManager = new DiagnosticsManager(jobName, jobId, containerModels, containerMb, containerNumCores, numPersistentStores, maxHeapSize, containerThreadPoolSize, "0", executionEnvContainerId, taskClassVersion, samzaVersion, hostname, diagnosticsSystemStream, mockSystemProducer, Duration.ofSeconds(1), mockExecutorService, autosizingEnabled); diagnosticsManager.start(); Mockito.verify(mockSystemProducer, Mockito.times(1)).start(); Mockito.verify(mockExecutorService, Mockito.times(1)) .scheduleWithFixedDelay(Mockito.any(Runnable.class), Mockito.anyLong(), Mockito.anyLong(), Mockito.any(TimeUnit.class)); }
Example #16
Source File: OperatorsTest.java From reactor-core with Apache License 2.0 | 6 votes |
@Test public void shouldBeSerialIfRacy() { for (int i = 0; i < 10000; i++) { long[] requested = new long[] { 0 }; Subscription mockSubscription = Mockito.mock(Subscription.class); Mockito.doAnswer(a -> requested[0] += (long) a.getArgument(0)).when(mockSubscription).request(Mockito.anyLong()); DeferredSubscription deferredSubscription = new DeferredSubscription(); deferredSubscription.request(5); RaceTestUtils.race(() -> deferredSubscription.set(mockSubscription), () -> { deferredSubscription.request(10); deferredSubscription.request(10); deferredSubscription.request(10); }); deferredSubscription.request(15); Assertions.assertThat(requested[0]).isEqualTo(50L); } }
Example #17
Source File: TestRecoverLeaseFSUtils.java From hbase with Apache License 2.0 | 6 votes |
/** * Test that isFileClosed makes us recover lease faster. */ @Test public void testIsFileClosed() throws IOException { // Make this time long so it is plain we broke out because of the isFileClosed invocation. HTU.getConfiguration().setInt("hbase.lease.recovery.dfs.timeout", 100000); CancelableProgressable reporter = Mockito.mock(CancelableProgressable.class); Mockito.when(reporter.progress()).thenReturn(true); IsFileClosedDistributedFileSystem dfs = Mockito.mock(IsFileClosedDistributedFileSystem.class); // Now make it so we fail the first two times -- the two fast invocations, then we fall into // the long loop during which we will call isFileClosed.... the next invocation should // therefore return true if we are to break the loop. Mockito.when(dfs.recoverLease(FILE)).thenReturn(false).thenReturn(false).thenReturn(true); Mockito.when(dfs.isFileClosed(FILE)).thenReturn(true); RecoverLeaseFSUtils.recoverFileLease(dfs, FILE, HTU.getConfiguration(), reporter); Mockito.verify(dfs, Mockito.times(2)).recoverLease(FILE); Mockito.verify(dfs, Mockito.times(1)).isFileClosed(FILE); }
Example #18
Source File: NodeDiscoveryDiscoverDevicesBlockTest.java From xbee-java with Mozilla Public License 2.0 | 6 votes |
/** * Test method for {@link com.digi.xbee.api.NodeDiscovery#discoverDevice(String)}. * * @throws Exception */ @Test public final void testDiscoverDeviceNoDevice() throws Exception { // Setup the resources for the test. String id = "id"; byte[] deviceTimeoutByteArray = new byte[]{0x01}; PowerMockito.when(deviceMock.getParameter("NT")).thenReturn(deviceTimeoutByteArray); // Call the method under test. RemoteXBeeDevice remote = nd.discoverDevice(id); // Verify the result. assertThat("The discovered device should be null", remote, is(equalTo(null))); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(SEND_NODE_DISCOVERY_COMMAND_METHOD, Mockito.anyString()); Mockito.verify(deviceMock, Mockito.times(1)).addPacketListener(packetListener); Mockito.verify(deviceMock, Mockito.times(1)).removePacketListener(packetListener); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(DISCOVER_DEVICES_API_METHOD, null, id); Mockito.verify(networkMock, Mockito.never()).addRemoteDevices(Mockito.anyListOf(RemoteXBeeDevice.class)); Mockito.verify(networkMock, Mockito.never()).addRemoteDevice(Mockito.any(RemoteXBeeDevice.class)); }
Example #19
Source File: PlanetHandlingTest.java From Open-Realms-of-Stars with GNU General Public License v2.0 | 6 votes |
@Test @Category(org.openRealmOfStars.UnitTest.class) public void testBasicFactoryBuildingScoring() { Building building = createBasicFactory(); Planet planet = Mockito.mock(Planet.class); Mockito.when(planet.getAmountMetalInGround()).thenReturn(5000); Mockito.when(planet.howManyBuildings(building.getName())).thenReturn(0); Mockito.when(planet.exceedRadiation()).thenReturn(false); PlayerInfo info = Mockito.mock(PlayerInfo.class); TechList techList = Mockito.mock(TechList.class); Mockito.when(info.getTechList()).thenReturn(techList); Mockito.when(info.getRace()).thenReturn(SpaceRace.HUMAN); Mockito.when(info.getGovernment()).thenReturn(GovernmentType.AI); Mockito.when(planet.getTotalProduction(Planet.PRODUCTION_PRODUCTION)).thenReturn(5); Mockito.when(planet.getTotalProduction(Planet.PRODUCTION_METAL)).thenReturn(5); int score = PlanetHandling.scoreBuilding(building, planet, info, Attitude.LOGICAL, false); assertEquals(59,score); }
Example #20
Source File: TestMockito.java From sarl with Apache License 2.0 | 5 votes |
/** Temporary fixing a bug in the class loading of Mockito 2. * * @param type the type to mock. * @return the mocked instance. * @see http://stackoverflow.com/questions/37702952/classnotfoundexception-with-mockito-2-in-osgi */ public static <T> T mock(Class<T> type) { if (type == null) { return null; } final ClassLoader loader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(Mockito.class.getClassLoader()); try { return Mockito.mock(type); } finally { Thread.currentThread().setContextClassLoader(loader); } }
Example #21
Source File: CachedRepoTestCase.java From charles-rest with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * CommandedRepo throws IOException if the http response * status is not appropriate. * @throws Exception If something goes wrong. */ @Test public void unexpectedHttpStatusFromBranchesAPI() throws Exception { int port = this.port(); MkContainer server = new MkGrizzlyContainer() .next(new MkAnswer.Simple(HttpURLConnection.HTTP_BAD_REQUEST)) .start(port); try { CachedRepo crepo = Mockito.spy( new CachedRepo(Mockito.mock(Repo.class)) ); Mockito.when(crepo.json()).thenReturn(Json .createObjectBuilder() .add( "branches_url", "http://localhost:" + port + "/branches{/branch}" ).build() ); crepo.hasGhPagesBranch(); fail("Expected an IOException here"); } catch (IOException ex) { assertTrue( ex.getMessage() .equals("Unexpected HTTP status response.") ); } finally { server.stop(); } }
Example #22
Source File: ParallelRunnerTest.java From incubator-gobblin with Apache License 2.0 | 5 votes |
@Test public void testMovePath() throws IOException, URISyntaxException { String expected = "test"; ByteArrayOutputStream actual = new ByteArrayOutputStream(); Path src = new Path("/src/file.txt"); Path dst = new Path("/dst/file.txt"); FileSystem fs1 = Mockito.mock(FileSystem.class); Mockito.when(fs1.exists(src)).thenReturn(true); Mockito.when(fs1.isFile(src)).thenReturn(true); Mockito.when(fs1.getUri()).thenReturn(new URI("fs1:////")); Mockito.when(fs1.getFileStatus(src)).thenReturn(new FileStatus(1, false, 1, 1, 1, src)); Mockito.when(fs1.open(src)) .thenReturn(new FSDataInputStream(new SeekableFSInputStream(new ByteArrayInputStream(expected.getBytes())))); Mockito.when(fs1.delete(src, true)).thenReturn(true); FileSystem fs2 = Mockito.mock(FileSystem.class); Mockito.when(fs2.exists(dst)).thenReturn(false); Mockito.when(fs2.getUri()).thenReturn(new URI("fs2:////")); Mockito.when(fs2.getConf()).thenReturn(new Configuration()); Mockito.when(fs2.create(dst, false)).thenReturn(new FSDataOutputStream(actual, null)); try (ParallelRunner parallelRunner = new ParallelRunner(1, fs1)) { parallelRunner.movePath(src, fs2, dst, Optional.<String>absent()); } Assert.assertEquals(actual.toString(), expected); }
Example #23
Source File: MonitoringRunnableTest.java From roboconf-platform with Apache License 2.0 | 5 votes |
private void testTheCommonChain( InstanceStatus status, String file ) throws Exception { // Create a model Instance rootInstance = new Instance( "root" ).component( new Component( "Root" ).installerName( Constants.TARGET_INSTALLER )); Instance childInstance = new Instance( "child" ).component( new Component( "Child" ).installerName( "whatever" )); InstanceHelpers.insertChild( rootInstance, childInstance ); this.agentInterface.setScopedInstance( rootInstance ); rootInstance.setStatus( status ); childInstance.setStatus( status ); // Create the resources File dir = InstanceHelpers.findInstanceDirectoryOnAgent( childInstance ); Utils.deleteFilesRecursively( dir ); Assert.assertTrue( dir.mkdirs()); File f = TestUtils.findTestFile( file ); String tmpDirLocation = System.getProperty( "java.io.tmpdir" ).replace( "\\", "/" ).replaceAll( "/?$", "" ); String updatedContent = Utils.readFileContent( f ).replace( "%TMP%", tmpDirLocation ); File measureFile = new File( dir, childInstance.getComponent().getName() + ".measures" ); Utils.writeStringInto( updatedContent, measureFile ); Assert.assertTrue( measureFile.exists()); // Run the task Mockito.verify( this.messagingClient, Mockito.times( 0 )).sendMessageToTheDm( Mockito.any( Message.class )); MonitoringRunnable task = new MonitoringRunnable( this.agentInterface, HANDLERS ); task.run(); Utils.deleteFilesRecursively( dir ); Assert.assertFalse( dir.exists()); File temporaryDirectory = new File( tmpDirLocation, "rbcf-test" ); Utils.deleteFilesRecursively( temporaryDirectory ); }
Example #24
Source File: TestUnitMergeRequestApi.java From gitlab4j-api with MIT License | 5 votes |
@Before public void setUp() throws Exception { initMocks(this); mockedResponse = new MockResponse(MergeRequest.class, "merge-request.json", null); when(mockGitLabApi.getApiClient()).thenReturn(mockedGitLabApiClient); when(mockedGitLabApiClient.validateSecretToken(any())).thenReturn(true); when(mockedGitLabApiClient.put(attributeCaptor.capture(), Mockito.<Object>any())) .thenReturn(mockedResponse); }
Example #25
Source File: ViewGroupMvpViewStateDelegateImplTest.java From mosby with Apache License 2.0 | 5 votes |
private void finishViewGroup(int detachCount, int destroyCount, boolean configChange, boolean finishingActivity) { Mockito.when(activity.isFinishing()).thenReturn(finishingActivity); Mockito.when(activity.isChangingConfigurations()).thenReturn(configChange); Mockito.when(callback.getPresenter()).thenReturn(presenter); delegate.onDetachedFromWindow(); savedState = delegate.onSaveInstanceState(); Mockito.verify(presenter, Mockito.times(detachCount)).detachView(); Mockito.verify(presenter, Mockito.times(destroyCount)).destroy(); }
Example #26
Source File: JpaPersistenceServiceImplJobsTest.java From genie with Apache License 2.0 | 5 votes |
@Test void noJobUnableToGetV4() { Mockito .when(this.jobRepository.findByUniqueId(Mockito.anyString(), Mockito.eq(IsV4JobProjection.class))) .thenReturn(Optional.empty()); Assertions .assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> this.persistenceService.isV4(UUID.randomUUID().toString())); }
Example #27
Source File: InkPerformerTest.java From Zen with GNU General Public License v2.0 | 5 votes |
private void disableRainbowDrawerInvocations() { Mockito.doNothing().when(rainbowDrawer).noStroke(); Mockito.doNothing().when(rainbowDrawer).smooth(); Mockito.doNothing().when(rainbowDrawer).tint(anyInt()); Mockito.doNothing().when(rainbowDrawer).pushMatrix(); Mockito.doNothing().when(rainbowDrawer).translate(anyFloat(), anyFloat()); Mockito.doNothing().when(rainbowDrawer).rotate(anyFloat()); Mockito.doNothing().when(rainbowDrawer).image(any(RainbowImage.class), anyFloat(), anyFloat(), anyFloat(), anyFloat()); Mockito.doNothing().when(rainbowDrawer).tint(anyInt()); Mockito.doNothing().when(rainbowDrawer).stroke(anyInt(), anyFloat()); Mockito.doNothing().when(rainbowDrawer).strokeWeight(anyFloat()); Mockito.doNothing().when(rainbowDrawer).line(anyFloat(), anyFloat(), anyFloat(), anyFloat()); }
Example #28
Source File: MockParameterFactory.java From junit5-extensions with MIT License | 5 votes |
@Override public Object getParameterValue(Parameter parameter) { Mock annotation = parameter.getAnnotation(Mock.class); MockSettings settings = Mockito.withSettings(); if (annotation.extraInterfaces().length > 0) { settings.extraInterfaces(annotation.extraInterfaces()); } if (annotation.serializable()) { settings.serializable(); } settings.name(annotation.name().isEmpty() ? parameter.getName() : annotation.name()); settings.defaultAnswer(annotation.answer()); return Mockito.mock(parameter.getType(), settings); }
Example #29
Source File: XBeeNetworkDiscoverDevicesListenerTest.java From xbee-java with Mozilla Public License 2.0 | 5 votes |
/** * Test method for {@link com.digi.xbee.api.XBeeNetwork#startDiscoveryProcess()}. * * <p>An {@code IllegalStateException} exception must be thrown when trying * to start a discovery process when it is already running.</p> */ @Test(expected=IllegalStateException.class) public void testStartDiscoveryProcessAlreadyRunning() { // Setup the resources for the test. Mockito.when(ndMock.isRunning()).thenReturn(true); // Call the method under test. network.startDiscoveryProcess(); }
Example #30
Source File: TestFragmentTracker.java From dremio-oss with Apache License 2.0 | 5 votes |
/** * Check that a dead node doesn't not trigger a successful query notification if * node managing the last major fragments (see DX-10956) */ @Test public void testNodeDead() { InOrder inOrder = Mockito.inOrder(completionListener); FragmentTracker fragmentTracker = new FragmentTracker(queryId, completionListener, () -> {}, null, new LocalExecutorSetService(DirectProvider.wrap(coordinator))); PlanFragmentFull fragment = new PlanFragmentFull( PlanFragmentMajor.newBuilder() .setHandle(FragmentHandle.newBuilder().setMajorFragmentId(0).setQueryId(queryId).build()) .build(), PlanFragmentMinor.newBuilder() .setAssignment(selfEndpoint) .build()); ExecutionPlan executionPlan = new ExecutionPlan(queryId, new Screen(OpProps.prototype(), null), 0, Collections .singletonList(fragment), null); observer.planCompleted(executionPlan); fragmentTracker.populate(executionPlan.getFragments(), new ResourceSchedulingDecisionInfo()); // Notify node is dead fragmentTracker.handleFailedNodes(ImmutableSet.of(selfEndpoint)); // Ideally, we should not even call succeeded... inOrder.verify(completionListener).failed(any(Exception.class)); inOrder.verify(completionListener).succeeded(); }