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 Project: samza   Author: apache   File: TestDiagnosticsManager.java    License: Apache License 2.0 6 votes vote down vote up
@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 #2
Source Project: smallrye-graphql   Author: smallrye   File: OpenTracingExecutionDecoratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #3
Source Project: datacollector   Author: streamsets   File: TestPipelineConfigurationValidator.java    License: Apache License 2.0 6 votes vote down vote up
@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 #4
@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 #5
Source Project: aws-mock   Author: treelogic-swe   File: TemplateUtilsTest.java    License: MIT License 6 votes vote down vote up
@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 #6
Source Project: olingo-odata4   Author: apache   File: ContextURLBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: api-layer   Author: zowe   File: ZosmfAuthenticationProviderTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@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 #8
Source Project: genie   Author: Netflix   File: JobRestControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #9
Source Project: xbee-java   Author: digidotcom   File: NodeDiscoveryDiscoverDevicesBlockTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source Project: Open-Realms-of-Stars   Author: tuomount   File: PlanetHandlingTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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 #11
Source Project: xbee-java   Author: digidotcom   File: IPv6DeviceReadDataTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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 #12
Source Project: arcusandroid   Author: arcus-smart-home   File: LawnAndGardenDeviceMoreControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #13
Source Project: nifi   Author: apache   File: TestVersionedFlowsResult.java    License: Apache License 2.0 6 votes vote down vote up
@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 #14
@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 #15
Source Project: tutorials   Author: eugenp   File: UserServiceUnitTest.java    License: MIT License 6 votes vote down vote up
@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 #16
Source Project: nifi   Author: apache   File: TestDeleteSQS.java    License: Apache License 2.0 6 votes vote down vote up
@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 #17
Source Project: hadoop   Author: naver   File: TestFailoverController.java    License: Apache License 2.0 6 votes vote down vote up
@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 #18
Source Project: reactor-core   Author: reactor   File: OperatorsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #19
Source Project: hbase   Author: apache   File: TestRecoverLeaseFSUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #20
Source Project: canon-sdk-java   Author: Blackdread   File: CameraObjectEventLogicDefaultMockTest.java    License: MIT License 5 votes vote down vote up
@BeforeEach
void setUp() {
    mockEdsdkLibrary();

    fakeCamera = new EdsdkLibrary.EdsCameraRef();
    cameraObjectListener = (event) -> countEvent.incrementAndGet();
    cameraObjectListenerThrows = (event) -> {
        throw new IllegalStateException("Always throw");
    };

    spyCameraObjectEventLogic = Mockito.spy(MockFactory.initialCanonFactory.getCameraObjectEventLogic());
}
 
Example #21
Source Project: graviteeio-access-management   Author: gravitee-io   File: ApplicationServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdate_technicalException() {
    PatchApplication patchClient = Mockito.mock(PatchApplication.class);
    when(applicationRepository.findById("my-client")).thenReturn(Maybe.error(TechnicalException::new));

    TestObserver testObserver = applicationService.patch(DOMAIN, "my-client", patchClient).test();
    testObserver.assertError(TechnicalManagementException.class);
    testObserver.assertNotComplete();

    verify(applicationRepository, times(1)).findById(anyString());
    verify(applicationRepository, never()).update(any(Application.class));
}
 
Example #22
Source Project: dockerfile-image-update   Author: salesforce   File: AllTest.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void checkPullRequestNotMadeForArchived() throws Exception {
    final String repoName = "mock repo";
    Map<String, Object> nsMap = ImmutableMap.of(Constants.IMG,
            "image", Constants.TAG,
            "tag", Constants.STORE,
            "store");
    Namespace ns = new Namespace(nsMap);

    GHRepository parentRepo = mock(GHRepository.class);
    GHRepository forkRepo = mock(GHRepository.class);
    DockerfileGitHubUtil dockerfileGitHubUtil = mock(DockerfileGitHubUtil.class);
    GHMyself myself = mock(GHMyself.class);

    when(parentRepo.isArchived()).thenReturn(true);

    when(forkRepo.getFullName()).thenReturn(repoName);
    when(parentRepo.getFullName()).thenReturn(repoName);
    when(dockerfileGitHubUtil.getRepo(eq(repoName))).thenReturn(forkRepo);
    when(forkRepo.isFork()).thenReturn(true);
    when(forkRepo.getParent()).thenReturn(parentRepo);
    when(dockerfileGitHubUtil.getMyself()).thenReturn(myself);

    Multimap<String, String> pathToDockerfilesInParentRepo = HashMultimap.create();
    pathToDockerfilesInParentRepo.put(repoName, null);

    All all = new All();
    all.loadDockerfileGithubUtil(dockerfileGitHubUtil);
    all.changeDockerfiles(ns, pathToDockerfilesInParentRepo, null, null, forkRepo, null);

    Mockito.verify(dockerfileGitHubUtil, Mockito.never())
            .createPullReq(Mockito.any(), anyString(), Mockito.any(), anyString());
    //Make sure we at least check if its archived
    Mockito.verify(parentRepo, Mockito.times(2)).isArchived();
}
 
Example #23
Source Project: CoachMarks   Author: myntra   File: PopUpCoachMarkPresenterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void setTypeFaceForDismissButtonNullTypeFaceTest() {
    Mockito.when(mTypeFaceProvider.getTypeFaceFromAssets(Matchers.anyString())).thenReturn(null);

    mPopUpCoachMarkPresenter.setTypeFaceForDismissButton(Matchers.anyString());

    Mockito.verify(mTypeFaceProvider, Mockito.times(1)).getTypeFaceFromAssets(Matchers.anyString());
    Mockito.verify(mPopUpCoachMarkPresentation, Mockito.times(0))
            .setTypeFaceForDismissButton((Typeface) Matchers.anyObject());

    Mockito.verifyNoMoreInteractions(mPopUpCoachMarkPresentation);
}
 
Example #24
Source Project: cloudstack   Author: apache   File: KVMStorageProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsEnoughSpaceForDownloadTemplateOnTemporaryLocationNotEnoughSpace() {
    String output = String.valueOf(templateSize - 30000L);
    Mockito.when(Script.runSimpleBashScript(Matchers.anyString())).thenReturn(output);
    boolean result = storageProcessor.isEnoughSpaceForDownloadTemplateOnTemporaryLocation(templateSize);
    Assert.assertFalse(result);
}
 
Example #25
Source Project: besu   Author: hyperledger   File: BesuCommandTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void rpcHttpCorsOriginsAllWithAnotherDomainMustFail() {
  parseCommand("--rpc-http-cors-origins=http://domain1.com,all");

  Mockito.verifyZeroInteractions(mockRunnerBuilder);

  assertThat(commandOutput.toString()).isEmpty();
  assertThat(commandErrorOutput.toString())
      .contains("Values '*' or 'all' can't be used with other domains");
}
 
Example #26
Source Project: conductor   Author: Netflix   File: WorkflowTaskCoordinatorTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTaskException() {
    Worker worker = Worker.create("test", task -> {
        throw new NoSuchMethodError();
    });
    TaskClient client = Mockito.mock(TaskClient.class);
    WorkflowTaskCoordinator coordinator = new WorkflowTaskCoordinator.Builder()
        .withWorkers(worker)
        .withThreadCount(1)
        .withWorkerQueueSize(1)
        .withSleepWhenRetry(100000)
        .withUpdateRetryCount(1)
        .withTaskClient(client)
        .withWorkerNamePrefix("test-worker-")
        .build();
    when(client.batchPollTasksInDomain(anyString(), isNull(), anyString(), anyInt(), anyInt())).thenReturn(ImmutableList.of(new Task()));
    when(client.ack(any(), any())).thenReturn(true);
    CountDownLatch latch = new CountDownLatch(1);
    doAnswer(invocation -> {
            assertEquals("test-worker-0", Thread.currentThread().getName());
            Object[] args = invocation.getArguments();
            TaskResult result = (TaskResult) args[0];
            assertEquals(TaskResult.Status.FAILED, result.getStatus());
            latch.countDown();
            return null;
        }
    ).when(client).updateTask(any());
    coordinator.init();
    Uninterruptibles.awaitUninterruptibly(latch);
    Mockito.verify(client).updateTask(any());
}
 
Example #27
Source Project: io   Author: fujitsu-pio   File: EsRetryTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * ドキュメント新規作成時_初回で根本例外IndexMissingExceptionが発生した場合にEsClient_EsIndexMissingExceptionが返されること.
 */
@Test(expected = EsClientException.EsIndexMissingException.class)
public void ドキュメント新規作成時_初回で根本例外IndexMissingExceptionが発生した場合にEsClient_EsIndexMissingExceptionが返されること() {
    PowerMockito.mockStatic(EsClientException.class);
    EsTypeImpl esTypeObject = Mockito.spy(new EsTypeImpl("dummy", "Test", "TestRoutingId", 0, 0, null));
    // EsType#asyncIndex()が呼ばれた場合に、根本例外にIndexMissingExceptionを含むElasticsearchExceptionを投げる。
    ElasticsearchException toBeThrown = new ElasticsearchException("dummy", new IndexNotFoundException("foo"));
    Mockito.doThrow(toBeThrown)
            .when(esTypeObject)
            .asyncIndex(Mockito.anyString(), Mockito.anyMapOf(String.class, Object.class),
                    Mockito.any(OpType.class), Mockito.anyLong());
    esTypeObject.create("dummyId", null);
    fail("EsIndexMissingException should be thrown.");
}
 
Example #28
Source Project: Volley-Ball   Author: lukaspili   File: LocalDispatcherTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldPostNoResponseWhenContentIsNull() throws Exception {
    // local request processor returns null reponse
    Mockito.when(mLocalRequestProcessor.getLocalResponse()).thenReturn(null);

    Assertions.assertThat(mLocalDispatcher.dispatch()).isEqualTo(true);
    Mockito.verify(mRequestQueue).take();
    Mockito.verify(mRequest).addMarker("local-queue-take");
    Mockito.verify(mRequest).addMarker("local-response-content-null-exit");
    Mockito.verify(mResponseDelivery).postEmptyIntermediateResponse(mRequest, BallResponse.ResponseSource.LOCAL);
    Mockito.verifyNoMoreInteractions(mResponseDelivery);
}
 
Example #29
Source Project: secure-data-service   Author: inbloom   File: SubscribeZoneConfiguratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigure() throws ADKException {
    Zone[] zones = {zone1, zone2, zone3};
    subscribeZoneConfigurator.configure(zones);
    Mockito.verify(zone1, Mockito.times(1)).connect(Mockito.anyInt());
    Mockito.verify(zone2, Mockito.times(1)).connect(Mockito.anyInt());
    Mockito.verify(zone3, Mockito.times(1)).connect(Mockito.anyInt());

    Assert.assertTrue(subscribeZoneConfigurator instanceof ZoneConfigurator);
}
 
Example #30
Source Project: mosby   Author: sockeqwe   File: ViewGroupMvpDelegateImplTest.java    License: Apache License 2.0 5 votes vote down vote up
private void startViewGroup(int createPresenter, int setPresenter, int attachView) {
  Mockito.when(callback.createPresenter()).thenReturn(presenter);

  if (savedState != null) {
    delegate.onRestoreInstanceState(savedState);
  }
  delegate.onAttachedToWindow();

  Mockito.verify(callback, Mockito.times(createPresenter)).createPresenter();
  Mockito.verify(callback, Mockito.times(setPresenter)).setPresenter(presenter);
  Mockito.verify(presenter, Mockito.times(attachView)).attachView(view);
}