类org.mockito.Mockito源码实例Demo

下面列出了怎么用org.mockito.Mockito的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: samza   文件: TestDiagnosticsManager.java
@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));
}
 
@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");
}
 
@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());;
}
 
@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);
}
 
源代码5 项目: aws-mock   文件: TemplateUtilsTest.java
@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);

}
 
源代码6 项目: olingo-odata4   文件: ContextURLBuilderTest.java
@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());
}
 
@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());
}
 
源代码8 项目: genie   文件: JobRestControllerTest.java
@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());
}
 
/**
 * 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));
}
 
源代码10 项目: Open-Realms-of-Stars   文件: PlanetHandlingTest.java
@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);
}
 
源代码11 项目: xbee-java   文件: IPv6DeviceReadDataTest.java
/**
 * 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);
}
 
@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);
}
 
源代码13 项目: nifi   文件: TestVersionedFlowsResult.java
@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));
}
 
@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);
}
 
源代码15 项目: tutorials   文件: UserServiceUnitTest.java
@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);
}
 
源代码16 项目: nifi   文件: TestDeleteSQS.java
@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);
}
 
源代码17 项目: hadoop   文件: TestFailoverController.java
@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);
}
 
源代码18 项目: reactor-core   文件: OperatorsTest.java
@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);
	}
}
 
源代码19 项目: hbase   文件: TestRecoverLeaseFSUtils.java
/**
 * 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);
}
 
@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());
}
 
@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));
}
 
源代码22 项目: dockerfile-image-update   文件: AllTest.java
@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();
}
 
源代码23 项目: CoachMarks   文件: PopUpCoachMarkPresenterTest.java
@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);
}
 
源代码24 项目: cloudstack   文件: KVMStorageProcessorTest.java
@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);
}
 
源代码25 项目: besu   文件: BesuCommandTest.java
@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");
}
 
源代码26 项目: conductor   文件: WorkflowTaskCoordinatorTests.java
@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());
}
 
源代码27 项目: io   文件: EsRetryTest.java
/**
 * ドキュメント新規作成時_初回で根本例外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.");
}
 
源代码28 项目: Volley-Ball   文件: LocalDispatcherTest.java
@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);
}
 
@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);
}
 
源代码30 项目: mosby   文件: ViewGroupMvpDelegateImplTest.java
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);
}
 
 类所在包
 同包方法