Java Code Examples for org.mockito.Mockito#mock()

The following examples show how to use org.mockito.Mockito#mock() . 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: TestCredentialStoresTaskImpl.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testLifecycle() {
  Configuration conf = new Configuration();
  StageLibraryTask libraryTask = Mockito.mock(StageLibraryTask.class);
  CredentialStoresTaskImpl storeTask = new CredentialStoresTaskImpl(null, conf, libraryTask, eventListenerManager);
  Map<String, CredentialStore> stores = storeTask.getStores();
  Assert.assertNotNull(stores);
  Assert.assertTrue(stores.isEmpty());

  storeTask = Mockito.spy(storeTask);

  Mockito.doReturn(Collections.emptyList()).when(storeTask).loadAndInitStores();

  // init
  storeTask.initTask();
  Mockito.verify(storeTask, Mockito.times(1)).loadAndInitStores();
  Assert.assertEquals(stores, CredentialEL.getCredentialStores());

  // stop
  CredentialStore store = Mockito.mock(CredentialStore.class);
  stores.put("id", store);
  storeTask.stopTask();
  Mockito.verify(store, Mockito.times(1)).destroy();
}
 
Example 2
Source File: TestNiFiClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetResourcesWithUserInputBeginning() throws Exception {
    ResourceLookupContext resourceLookupContext = Mockito.mock(ResourceLookupContext.class);
    when(resourceLookupContext.getUserInput()).thenReturn("/pr");

    final List<String> expectedResources = new ArrayList<>();
    expectedResources.add("/provenance");
    expectedResources.add("/proxy");

    List<String> resources = niFiClient.getResources(resourceLookupContext);
    Assert.assertNotNull(resources);
    Assert.assertEquals(expectedResources.size(), resources.size());

    resources.removeAll(expectedResources);
    Assert.assertEquals(0, resources.size());
}
 
Example 3
Source File: GithubSCMSourceBranchesTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void testExistingMultipleBranchesWithNoDefault() throws IOException {
    // Situation: Hitting github and getting back multiple branches where master is not in the list
    githubApi.stubFor(
            get(urlEqualTo("/repos/cloudbeers/yolo/branches"))
                    .willReturn(
                            aResponse()
                                    .withHeader("Content-Type", "application/json; charset=utf-8")
                                    .withBodyFile("../branches/_files/body-yolo-branches-existent-multiple-branches-no-master.json")));
    SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class);
    GitHubSCMSourceContext context = new GitHubSCMSourceContext(null, mockSCMHeadObserver);
    context.wantTags(true);
    GitHubSCMSourceRequest request = context.newRequest(new GitHubSCMSource("cloudbeers", "yolo", null, false), null);
    Iterator<GHBranch> branches = new GitHubSCMSource.LazyBranches(request, repo).iterator();
    // Expected: In the iterator will be a multiple branches named existent-branch2 and existent-branch1
    assertTrue(branches.hasNext());
    assertEquals("existent-branch1", branches.next().getName());
    assertTrue(branches.hasNext());
    assertEquals("existent-branch2", branches.next().getName());
}
 
Example 4
Source File: TestUserREST.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test12DeactivateUser() {
	XXPortalUser xxPUserExp = new XXPortalUser();
	xxPUserExp = null;
	XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class);

	Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao);
	Mockito.when(xxPortalUserDao.getById(userId)).thenReturn(xxPUserExp);
	Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(),
			Mockito.nullable(Long.class), Mockito.nullable(String.class), Mockito.anyString())).thenReturn(new WebApplicationException());
	thrown.expect(WebApplicationException.class);

	userREST.deactivateUser(userId);

	Mockito.verify(daoManager).getXXPortalUser();
	Mockito.verify(xxPortalUserDao).getById(userId);
	Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(),
			Mockito.anyLong(), Mockito.anyString(), Mockito.anyString());
}
 
Example 5
Source File: TestHttpServer.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequiresAuthorizationAccess() throws Exception {
  Configuration conf = new Configuration();
  ServletContext context = Mockito.mock(ServletContext.class);
  Mockito.when(context.getAttribute(HttpServer2.CONF_CONTEXT_ATTRIBUTE)).thenReturn(conf);
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

  //requires admin access to instrumentation, FALSE by default
  Assert.assertTrue(HttpServer2.isInstrumentationAccessAllowed(context, request, response));

  //requires admin access to instrumentation, TRUE
  conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_INSTRUMENTATION_REQUIRES_ADMIN, true);
  conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, true);
  AccessControlList acls = Mockito.mock(AccessControlList.class);
  Mockito.when(acls.isUserAllowed(Mockito.<UserGroupInformation>any())).thenReturn(false);
  Mockito.when(context.getAttribute(HttpServer2.ADMINS_ACL)).thenReturn(acls);
  Assert.assertFalse(HttpServer2.isInstrumentationAccessAllowed(context, request, response));
}
 
Example 6
Source File: WriteCommandTest.java    From neatle with MIT License 6 votes vote down vote up
@Test
public void testOnCharacteristicWriteNextChunk() throws IOException {
    when(gatt.getService(eq(serviceUUID))).thenReturn(gattService);
    when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic);
    when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true);
    InputSource inputSource = Mockito.mock(InputSource.class);
    when(inputSource.nextChunk()).thenReturn(new byte[]{12, 21});

    writeCommand = new WriteCommand(
            serviceUUID,
            characteristicUUID,
            BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
            inputSource,
            commandObserver);

    writeCommand.execute(device, operationCommandObserver, gatt);

    writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS);
    verify(commandObserver, times(0)).finished(any(Command.class), any(CommandResult.class));
    verify(operationCommandObserver, times(0)).finished(any(Command.class), any(CommandResult.class));
}
 
Example 7
Source File: StreamUtilsTest.java    From stream-utils with Apache License 2.0 5 votes vote down vote up
/**
 * This test is proves that the streamy way works.
 */
@Test(timeout = 1000)
public void testBufferStreamy() {
    // Create a mock supplier, that way we know how many times get was called
    Supplier<Integer> supplier = Mockito.mock(Supplier.class);
    Mockito.when(supplier.get()).thenReturn(0);

    final Stream<Integer> infiniteStream = Stream.generate(supplier);
    final Stream<List<Integer>> groupedStream = StreamUtils.buffer(infiniteStream.limit(1000000000), 10);
    assertEquals(groupedStream.findFirst().get(), Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));

    // get should only be called 11 times because we're buffering 10, and we retrieve the
    // 11th to do the check that we're over the limit
    Mockito.verify(supplier, Mockito.times(11)).get();
}
 
Example 8
Source File: Auth0Test.java    From Auth0.Android with MIT License 5 votes vote down vote up
@Test
public void shouldFailToBuildFromResourcesWithoutClientID() {
    Resources resources = Mockito.mock(Resources.class);
    when(context.getResources()).thenReturn(resources);
    when(resources.getIdentifier(eq("com_auth0_client_id"), eq("string"), anyString())).thenReturn(0);
    when(resources.getIdentifier(eq("com_auth0_domain"), eq("string"), anyString())).thenReturn(333);

    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("The 'R.string.com_auth0_client_id' value it's not defined in your project's resources file.");

    new Auth0(context);
}
 
Example 9
Source File: JobFieldModelTest.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
@Test
public void fieldModelsTest() {
    String testJobId = "test-job-id";
    FieldModel testFieldModel = Mockito.mock(FieldModel.class);
    FieldModel newTestFieldModel = Mockito.mock(FieldModel.class);

    Set<FieldModel> fieldModels = Set.of(testFieldModel);
    Set<FieldModel> newFieldModels = Set.of(testFieldModel, newTestFieldModel);
    JobFieldModel testJobFieldModel = new JobFieldModel(testJobId, fieldModels);
    testJobFieldModel.setFieldModels(newFieldModels);

    assertEquals(newFieldModels, testJobFieldModel.getFieldModels());
    assertEquals(2, testJobFieldModel.getFieldModels().size());
}
 
Example 10
Source File: HeartTest.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Test
public void testBeat_distributedStorage_eachDatacenterAvailability_repairs_noMetrics()
    throws InterruptedException, ReaperException {

  AppContext context = new AppContext();
  context.config = new ReaperApplicationConfiguration();
  context.config.setDatacenterAvailability(ReaperApplicationConfiguration.DatacenterAvailability.EACH);

  context.repairManager = RepairManager.create(
      context,
      Executors.newScheduledThreadPool(1),
      REPAIR_TIMEOUT_S,
      TimeUnit.SECONDS,
      RETRY_DELAY_S,
      TimeUnit.SECONDS);

  context.repairManager.repairRunners.put(UUID.randomUUID(), Mockito.mock(RepairRunner.class));
  context.repairManager.repairRunners.put(UUID.randomUUID(), Mockito.mock(RepairRunner.class));

  context.storage = Mockito.mock(CassandraStorage.class);
  context.jmxConnectionFactory = Mockito.mock(JmxConnectionFactory.class);

  Mockito
      .when(((CassandraStorage)context.storage).getNodeMetrics(any()))
      .thenReturn(Collections.emptyList());

  try (Heart heart = Heart.create(context)) {
    context.isDistributed.set(true);
    heart.beat();
    Thread.sleep(500);
  }

  Mockito.verify((CassandraStorage)context.storage, Mockito.times(1)).saveHeartbeat();
  Mockito.verify((CassandraStorage)context.storage, Mockito.times(2)).getNodeMetrics(any());
  Mockito.verify(context.jmxConnectionFactory, Mockito.times(0)).connectAny(any(Collection.class));
  Mockito.verify((CassandraStorage)context.storage, Mockito.times(0)).storeNodeMetrics(any(), any());
}
 
Example 11
Source File: ResourceHandlerRegistryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resourceChainWithOverrides() throws Exception {
	CachingResourceResolver cachingResolver = Mockito.mock(CachingResourceResolver.class);
	VersionResourceResolver versionResolver = Mockito.mock(VersionResourceResolver.class);
	WebJarsResourceResolver webjarsResolver = Mockito.mock(WebJarsResourceResolver.class);
	PathResourceResolver pathResourceResolver = new PathResourceResolver();
	CachingResourceTransformer cachingTransformer = Mockito.mock(CachingResourceTransformer.class);
	AppCacheManifestTransformer appCacheTransformer = Mockito.mock(AppCacheManifestTransformer.class);
	CssLinkResourceTransformer cssLinkTransformer = new CssLinkResourceTransformer();

	this.registration.setCachePeriod(3600)
			.resourceChain(false)
				.addResolver(cachingResolver)
				.addResolver(versionResolver)
				.addResolver(webjarsResolver)
				.addResolver(pathResourceResolver)
				.addTransformer(cachingTransformer)
				.addTransformer(appCacheTransformer)
				.addTransformer(cssLinkTransformer);

	ResourceHttpRequestHandler handler = getHandler("/resources/**");
	List<ResourceResolver> resolvers = handler.getResourceResolvers();
	assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4));
	assertThat(resolvers.get(0), Matchers.sameInstance(cachingResolver));
	assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver));
	assertThat(resolvers.get(2), Matchers.sameInstance(webjarsResolver));
	assertThat(resolvers.get(3), Matchers.sameInstance(pathResourceResolver));

	List<ResourceTransformer> transformers = handler.getResourceTransformers();
	assertThat(transformers, Matchers.hasSize(3));
	assertThat(transformers.get(0), Matchers.sameInstance(cachingTransformer));
	assertThat(transformers.get(1), Matchers.sameInstance(appCacheTransformer));
	assertThat(transformers.get(2), Matchers.sameInstance(cssLinkTransformer));
}
 
Example 12
Source File: StackTraceFormatterTest.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
@Test
public void testFormat() throws Exception {
    //given
    final JumpToCodeService mock = Mockito.mock(JumpToCodeService.class);
    Mockito.when(mock.getContentOptional(Mockito.any(LocationInfo.class))).thenAnswer(invocation -> {
        LocationInfo li = (LocationInfo) invocation.getArguments()[0];
        return li.getLineNumber().map(l->l + ": code");
    });
    final StackTraceFormatter formatter = new StackTraceFormatter(mock);

    //when
    String message = "java.util.concurrent.ExecutionException: java.io.IOException: Error executing request, connection broken.... :)\n" +
      "\tat java.util.concurrent.FutureTask.report(FutureTask.java:122)\n" +
      "\tat test.sampleapp.SampleAppMultiThreadedFix2.lambda$performRequests$16(SampleAppMultiThreadedFix2.java:36)\n" +
      "\tat test.sampleapp.SampleAppMultiThreadedFix2$$Lambda$16/2016207428.accept(Unknown Source)\n" +
      "Caused by: java.io.IOException: Error executing request, connection broken.... :)\n" +
      "\tat test.sampleapp.services.hotels.HotelsService.getHotels(HotelsService.java:30)\n" +
      "\tat test.sampleapp.SampleAppMultiThreadedFix2$$Lambda$9/1549863774.call(Unknown Source)\n" +
      "\tat test.sampleapp.executors.MdcCallableWrapper.call(MdcCallableWrapper.java:32)\n" +
      "\t... 4 more";
    final String format = formatter.format(message);

    //then
    String expected = "java.util.concurrent.ExecutionException: java.io.IOException: Error executing request, connection broken.... :)\n" +
      "  at java.util.concurrent.FutureTask.report(FutureTask.java:122)\t //code\n" +
      "  at test.sampleapp.SampleAppMultiThreadedFix2.lambda$performRequests$16(SampleAppMultiThreadedFix2.java:36)\t //code\n" +
      "  at test.sampleapp.SampleAppMultiThreadedFix2$$Lambda$16/2016207428.accept(Unknown Source)\n" +
      "Caused by: java.io.IOException: Error executing request, connection broken.... :)\n" +
      "  at test.sampleapp.services.hotels.HotelsService.getHotels(HotelsService.java:30)\t //code\n" +
      "  at test.sampleapp.SampleAppMultiThreadedFix2$$Lambda$9/1549863774.call(Unknown Source)\n" +
      "  at test.sampleapp.executors.MdcCallableWrapper.call(MdcCallableWrapper.java:32)\t //code\n" +
      "\t... 4 more";
    Assert.assertEquals(format, expected);

}
 
Example 13
Source File: SifIdResolverCustomDataTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void getSliGuidByTypeShouldHandleNull() throws Exception {
    setupCustomDataMocking();

    Entity entity = Mockito.mock(Entity.class);
    when(entity.getId()).thenReturn(SLI_ID4);
    List<Entity> queryResult = Arrays.asList(new Entity[] {});
    when(mockSlcInterface.read(eq(SLI_TYPE4), any(Query.class))).thenReturn(queryResult);

    String result = resolver.getSliGuidByType(SIF_REF_ID4, SLI_TYPE4, ZONE_ID1);

    Assert.assertNull(result);
}
 
Example 14
Source File: BoolTasteTest.java    From Favor with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    sharedPreferences = Mockito.mock(SharedPreferences.class);
    Mockito.when(sharedPreferences.getBoolean("key", true)).thenReturn(true);
    editor = Mockito.mock(SharedPreferences.Editor.class);
    BoolTaste = new Taste.BoolTaste(sharedPreferences, "key", defaultValues);
}
 
Example 15
Source File: HttpBasicHelperTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Test
public void tryToExtractUsernameAndPasswordFromEmptyHeader() {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getHeader("Authorization")).thenReturn("");

    final String[] credentials = HttpBasicHelper.extractUsernameAndPasswordFromBasicHeader(request);
    assertThat(credentials).isNotNull();
    assertThat(credentials[0]).isEqualTo("");
    assertThat(credentials[1]).isEqualTo("");
}
 
Example 16
Source File: JpaPersistenceServiceImplJobsTest.java    From genie with Apache License 2.0 5 votes vote down vote up
@Test
void cantGetJobCommandIfCommandDoesNotExist() {
    final String id = UUID.randomUUID().toString();
    final JobEntity entity = Mockito.mock(JobEntity.class);
    Mockito.when(entity.getCommand()).thenReturn(Optional.empty());
    Mockito.when(this.jobRepository.findByUniqueId(id, JobCommandProjection.class)).thenReturn(Optional.of(entity));
    Assertions
        .assertThatExceptionOfType(NotFoundException.class)
        .isThrownBy(() -> this.persistenceService.getJobCommand(id));
}
 
Example 17
Source File: IconServletTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGet() throws Exception {

	// Prepare the servlet
	File configurationDirectory = this.folder.newFolder();

	this.manager = new Manager();
	this.manager.configurationMngr().setWorkingDirectory( configurationDirectory );

	File appDir = ConfigurationUtils.findApplicationDirectory( "app", configurationDirectory );
	File descDir = new File( appDir, Constants.PROJECT_DIR_DESC );
	Assert.assertTrue( descDir.mkdirs());

	IconServlet servlet = new IconServlet( this.manager );

	// Add a fake file
	File trickFile = new File( descDir, "directory.jpg" );
	Assert.assertTrue( trickFile.mkdirs());

	// Prepare our mocks
	HttpServletRequest req = Mockito.mock( HttpServletRequest.class );
	HttpServletResponse resp = Mockito.mock( HttpServletResponse.class );

	Mockito.when( req.getPathInfo()).thenReturn( "/app/whatever.jpg" );
	servlet.doGet( req, resp );
	Mockito.verify( resp ).setStatus( HttpServletResponse.SC_NOT_FOUND );

	// Now, add a real icon and make sure it is returned
	// (it is returned if a MIME type was set).
	File singleJpgFile = new File( descDir, "whatever.jpg" );
	Assert.assertTrue( singleJpgFile.createNewFile());

	ServletOutputStream out = Mockito.mock( ServletOutputStream.class );
	Mockito.when( resp.getOutputStream()).thenReturn( out );
	servlet.doGet( req, resp );
	Mockito.verify( resp ).setContentType( IconUtils.MIME_JPG );
}
 
Example 18
Source File: FirestoreRepositoryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
public FirestoreTemplate firestoreTemplate(
		FirestoreClassMapper classMapper, FirestoreMappingContext firestoreMappingContext) {
	FirestoreTemplate template = Mockito.mock(FirestoreTemplate.class);
	Mockito.when(template.getClassMapper()).thenReturn(classMapper);
	Mockito.when(template.getMappingContext()).thenReturn(firestoreMappingContext);
	Mockito.when(template.execute(any(), any())).thenReturn(Flux.empty());
	return template;
}
 
Example 19
Source File: SecureJobTemplateTest.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Test
public void test() {

	SecureJobTemplate template = Mockito.mock(SecureJobTemplate.class);
	Mockito.when(template.getUri()).thenReturn(URI.create("my://template"));
	Mockito.when(template.isSecure()).thenReturn(true);
	Mockito.when(template.overridableProperties()).thenReturn(Lists.newArrayList("my.overridable.property1", "my.overridable.property2"));

	// Test simple filtering
	Config config = ConfigFactory.parseMap(ImmutableMap.of(
			"someProperty", "foo",
			"my.overridable.property1", "bar"
	));
	Config result = SecureJobTemplate.filterUserConfig(template, config, log);
	Assert.assertEquals(result.entrySet().size(), 1);
	Assert.assertEquals(result.getString("my.overridable.property1"), "bar");
	Assert.assertFalse(result.hasPath("someProperty"));
	Assert.assertFalse(result.hasPath("my.overridable.property2"));

	// Test allowing override of a subconfig
	config = ConfigFactory.parseMap(ImmutableMap.of(
			"someProperty", "foo",
			"my.overridable.property1.key1", "bar",
			"my.overridable.property1.key2", "baz"
	));
	result = SecureJobTemplate.filterUserConfig(template, config, log);
	Assert.assertEquals(result.entrySet().size(), 2);
	Assert.assertEquals(result.getString("my.overridable.property1.key1"), "bar");
	Assert.assertEquals(result.getString("my.overridable.property1.key2"), "baz");

	// Test multiple overrides
	config = ConfigFactory.parseMap(ImmutableMap.of(
			"someProperty", "foo",
			"my.overridable.property1", "bar",
			"my.overridable.property2", "baz"
	));
	result = SecureJobTemplate.filterUserConfig(template, config, log);
	Assert.assertEquals(result.entrySet().size(), 2);
	Assert.assertEquals(result.getString("my.overridable.property1"), "bar");
	Assert.assertEquals(result.getString("my.overridable.property2"), "baz");
}
 
Example 20
Source File: VmwareDatacenterApiUnitTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Bean
public AgentManager agentManager() {
    return Mockito.mock(AgentManager.class);
}