Java Code Examples for org.springframework.test.util.ReflectionTestUtils

The following examples show how to use org.springframework.test.util.ReflectionTestUtils. These examples are extracted from open source projects. 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: e-commerce-microservice   Source File: WebConfigurerTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void testCustomizeServletContainer() {
    env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
    UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
    webConfigurer.customize(container);
    assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
    assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
    assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
    if (container.getDocumentRoot() != null) {
        assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
    }

    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
 
Example 2
Source Project: cosmic   Source File: AccountManagerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {
    accountManager = new AccountManagerImpl();
    for (final Field field : AccountManagerImpl.class.getDeclaredFields()) {
        if (field.getAnnotation(Inject.class) != null) {
            field.setAccessible(true);
            try {
                final Field mockField = this.getClass().getDeclaredField(
                        field.getName());
                field.set(accountManager, mockField.get(this));
            } catch (final Exception e) {
                // ignore missing fields
            }
        }
    }
    ReflectionTestUtils.setField(accountManager, "_userAuthenticators", Arrays.asList(userAuthenticator));
    accountManager.setSecurityCheckers(Arrays.asList(securityChecker));
    CallContext.register(callingUser, callingAccount);
}
 
Example 3
@Test
public void testAuthenticateJwt() {
    AuthenticationService authenticationService = mock(AuthenticationService.class);
    ZosmfService zosmfService = mock(ZosmfService.class);
    ZosmfAuthenticationProvider zosmfAuthenticationProvider = new ZosmfAuthenticationProvider(authenticationService, zosmfService);
    ReflectionTestUtils.setField(zosmfAuthenticationProvider, "useJwtToken", Boolean.TRUE);
    Authentication authentication = mock(Authentication.class);
    when(authentication.getPrincipal()).thenReturn("user1");
    TokenAuthentication authentication2 = mock(TokenAuthentication.class);

    when(zosmfService.authenticate(authentication)).thenReturn(new ZosmfService.AuthenticationResponse(
        "domain1",
        Collections.singletonMap(ZosmfService.TokenType.JWT, "jwtToken1")
    ));
    when(authenticationService.createTokenAuthentication("user1", "jwtToken1")).thenReturn(authentication2);

    assertSame(authentication2, zosmfAuthenticationProvider.authenticate(authentication));
}
 
Example 4
Source Project: pacbot   Source File: AssetServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testgetAssetGroupInfo() throws Exception {

    Map<String, Object> agMap1 = new HashMap<>();
    agMap1.put("name", "testDomain");

    List<Map<String, Object>> agList = new ArrayList<>();
    agList.add(agMap1);

    when(assetRepository.getAssetGroupInfo(anyString())).thenReturn(agMap1);
    when(assetRepository.getApplicationByAssetGroup(anyString())).thenReturn(Arrays.asList("pacman", "monitor"));
    ReflectionTestUtils.setField(service, "repository", assetRepository);

    Map<String, Object> a = service.getAssetGroupInfo("testAg");
    System.out.println(a);
    assertTrue(a.size() == 4);

}
 
Example 5
Source Project: pacbot   Source File: AssetControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testgetAssetGroupInfo() throws Exception {
    List<Map<String, Object>> tTypeList = new ArrayList<>();
    Map<String, Object> tTypeMap = new HashMap<>();
    
    when(service.getAssetGroupInfo("ag")).thenReturn(tTypeMap);
    ReflectionTestUtils.setField(controller, "assetService", service);

    ResponseEntity<Object> responseObj0 = controller.getAssetGroupInfo("ag");
    assertTrue(responseObj0.getStatusCode() == HttpStatus.EXPECTATION_FAILED);
    
    tTypeMap.put("name", "aws-all");
    tTypeList.add(tTypeMap);

    when(service.getAssetGroupInfo("ag")).thenReturn(tTypeMap);
    ReflectionTestUtils.setField(controller, "assetService", service);

    ResponseEntity<Object> responseObj = controller.getAssetGroupInfo("ag");
    assertTrue(responseObj.getStatusCode() == HttpStatus.OK);
    assertTrue(((Map<String, Object>) responseObj.getBody()).get("data") != null);
}
 
Example 6
@Test
public void testDefaultConfiguration() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class);
	this.context.refresh();
	this.context.getBean(AUTHORIZATION_SERVER_CONFIG);
	this.context.getBean(RESOURCE_SERVER_CONFIG);
	this.context.getBean(OAuth2MethodSecurityConfiguration.class);
	ClientDetails config = this.context.getBean(BaseClientDetails.class);
	AuthorizationEndpoint endpoint = this.context.getBean(AuthorizationEndpoint.class);
	UserApprovalHandler handler = (UserApprovalHandler) ReflectionTestUtils.getField(endpoint,
			"userApprovalHandler");
	ClientDetailsService clientDetailsService = this.context.getBean(ClientDetailsService.class);
	ClientDetails clientDetails = clientDetailsService.loadClientByClientId(config.getClientId());
	assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService)).isTrue();
	assertThat(AopUtils.getTargetClass(clientDetailsService).getName())
			.isEqualTo(InMemoryClientDetailsService.class.getName());
	assertThat(handler).isInstanceOf(ApprovalStoreUserApprovalHandler.class);
	assertThat(clientDetails).isEqualTo(config);
	verifyAuthentication(config);
	assertThat(this.context.getBeanNamesForType(OAuth2RestOperations.class)).isEmpty();
}
 
Example 7
Source Project: pmq   Source File: ConsumerCommitServiceImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
	consumerCommitServiceImpl = new ConsumerCommitServiceImpl();
	queueOffsetService = mock(QueueOffsetService.class);
	SoaConfig soaConfig = new SoaConfig();
	Environment env = mock(Environment.class);
	ReflectionTestUtils.setField(soaConfig, "env", env);
	ReflectionTestUtils.setField(consumerCommitServiceImpl, "queueOffsetService", queueOffsetService);
	ReflectionTestUtils.setField(consumerCommitServiceImpl, "soaConfig", soaConfig);
	when(env.getProperty(anyString(), anyString())).thenAnswer(new Answer<String>() {
		@Override
		public String answer(InvocationOnMock invocation) throws Throwable {
			Object[] args = invocation.getArguments();
			return (String) args[1];
		}
	});
}
 
Example 8
Source Project: pacbot   Source File: CertificateRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getCerticatesSummaryTest_Exception() throws Exception {
    
    when(complianceRepository.getCertificates(anyString())).thenReturn(new HashMap<>());
    ReflectionTestUtils.setField(certificateRepository, "complianceRepository", complianceRepository);
    mockStatic(PacHttpUtils.class);
    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenThrow(new Exception());
    ReflectionTestUtils.setField(certificateRepository, "esUrl", "dummyEsURL");
    
    assertThatThrownBy(() -> certificateRepository.getCertificatesSummary("ag"))
    .isInstanceOf(DataException.class);
    
    when(complianceRepository.getCertificates(anyString())).thenThrow(new DataException());
    ReflectionTestUtils.setField(certificateRepository, "complianceRepository", complianceRepository);
    
    assertThatThrownBy(() -> certificateRepository.getCertificatesSummary("ag"))
    .isInstanceOf(DataException.class);
}
 
Example 9
Source Project: pacbot   Source File: AssetListControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testgetEditableFieldsByTargetType() throws Exception{
    ResponseEntity<Object> responseObj1 = controller.getEditableFieldsByTargetType("","ec2");
    assertTrue(responseObj1.getStatusCode()==HttpStatus.EXPECTATION_FAILED);
   
    List<Map<String, Object>> aList = new ArrayList<>();
    Map<String,Object> aMap = new HashMap<>();
    aMap.put("type", "ec2");
    aList.add(aMap);
    
    when(service.getTargetTypesForAssetGroup(anyString(),anyString(),anyString())).thenReturn(aList);
    ReflectionTestUtils.setField(controller, "assetService", service);
    ResponseEntity<Object> responseObj2 = controller.getEditableFieldsByTargetType("ag","ec2");
    assertTrue(responseObj2.getStatusCode()==HttpStatus.OK);
    
    ResponseEntity<Object> responseObj3 = controller.getEditableFieldsByTargetType("ag","s3");
    assertTrue(responseObj3.getStatusCode()==HttpStatus.EXPECTATION_FAILED);
  
}
 
Example 10
@Test
public void testCustomizeServletContainer() {
    env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
    UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
    webConfigurer.customize(container);
    assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
    assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
    assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
    if (container.getDocumentRoot() != null) {
        assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www"));
    }

    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
 
Example 11
@Test(expected = DocumentCryptException.class)
@DirtiesContext
public void checkWrongKeyRoot() {
    // save to db, version = 0
    MyBean bean = new MyBean();
    bean.secretString = "secret";
    bean.nonSensitiveData = getClass().getSimpleName();
    mongoTemplate.insert(bean);

    // override version 0's key
    ReflectionTestUtils.setField(cryptVault, "cryptVersions", new CryptVersion[256]);
    cryptVault.with256BitAesCbcPkcs5PaddingAnd128BitSaltKey(0, Base64.getDecoder().decode("aic7QGYCCSHyy7gYRCyNTpPThbomw1/dtWl4bocyTnU="));

    try {
        mongoTemplate.find(query(where(MONGO_NONSENSITIVEDATA).is(getClass().getSimpleName())), MyBean.class);
    } catch (DocumentCryptException e) {
        assertCryptException(e, "mybean", null, "secretString");
        throw e;
    }
}
 
Example 12
Source Project: pacbot   Source File: ESManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "static-access" })
@Test 
public void deleteOldDocumentsTest() throws Exception{
    
    HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
    when(response.getEntity()).thenReturn(jsonEntity);
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenReturn(response);
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    
    esManager.deleteOldDocuments("index", "type", "field","value");
    
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenThrow(new IOException());
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    esManager.deleteOldDocuments("index", "type", "field","value");
}
 
Example 13
@Test(expected = DocumentCryptException.class)
@DirtiesContext
public void checkWrongKeyCustomId() {
    // save to db, version = 0
    MyBean bean = new MyBean();
    bean.id = "customId";
    bean.secretString = "secret";
    bean.nonSensitiveData = getClass().getSimpleName();
    mongoTemplate.insert(bean);

    // override version 0's key
    ReflectionTestUtils.setField(cryptVault, "cryptVersions", new CryptVersion[256]);
    cryptVault.with256BitAesCbcPkcs5PaddingAnd128BitSaltKey(0, Base64.getDecoder().decode("aic7QGYCCSHyy7gYRCyNTpPThbomw1/dtWl4bocyTnU="));

    try {
        mongoTemplate.find(query(where(MONGO_NONSENSITIVEDATA).is(getClass().getSimpleName())), MyBean.class);
    } catch (DocumentCryptException e) {
        assertCryptException(e, "mybean", null, "secretString");
        throw e;
    }
}
 
Example 14
Source Project: x-pipe   Source File: KeeperContainerServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    keeperContainerService = new KeeperContainerService();

    ReflectionTestUtils.setField(keeperContainerService, "leaderElectorManager", leaderElectorManager);
    ReflectionTestUtils.setField(keeperContainerService, "leaderElectorManager", leaderElectorManager);
    ReflectionTestUtils.setField(keeperContainerService, "keeperContainerConfig", keeperContainerConfig);
    ReflectionTestUtils.setField(keeperContainerService, "keeperConfig", keeperConfig);
    ReflectionTestUtils.setField(keeperContainerService, "keepersMonitorManager", keepersMonitorManager);

    someCluster = "someCluster";
    someShard = "someShard";
    somePort = 6789;

    someKeeperMeta = new KeeperMeta();
    someKeeperMeta.setPort(somePort);
    someKeeperTransMeta = new KeeperTransMeta();
    someKeeperTransMeta.setClusterId(someCluster);
    someKeeperTransMeta.setShardId(someShard);
    someKeeperTransMeta.setKeeperMeta(someKeeperMeta);

    when(keeperContainerConfig.getReplicationStoreDir()).thenReturn(System.getProperty("user.dir"));

    ReflectionTestUtils.setField(ComponentRegistryHolder.class, "componentRegistry", componentRegistry);
}
 
Example 15
Source Project: pacbot   Source File: ComplianceRepositoryImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void updateKernelVersionTest() throws Exception {
    KernelVersion kernelVersion = new KernelVersion();
    kernelVersion.setInstanceId("12345");
    kernelVersion.setKernelVersionId("12345");
    String response = "{\"count\":0,\"_shards\":{\"total\":3,\"successful\":3,\"failed\":0}}";
    String responsewithcount = "{\"count\":10,\"_shards\":{\"total\":3,\"successful\":3,\"failed\":0}}";
    ReflectionTestUtils.setField(complianceRepositoryImpl, "esUrl", "dummyEsURL");
    String kernelCriteria = "el6.x#2.6333.32-696.23.1.el6.x86_64|el7#3.10.0-6933333.231.1.el7.x86_64|el6uek#3.8.13-133318.20.3.el6uek-x86_64|amzn1#4.9.85-38.55558.amzn1.x86_64";

    when(rdsepository.queryForString(anyString())).thenReturn(kernelCriteria);
    mockStatic(PacHttpUtils.class);

    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenReturn(responsewithcount);
    complianceRepositoryImpl.updateKernelVersion(kernelVersion);
    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenReturn(response);
    complianceRepositoryImpl.updateKernelVersion(kernelVersion);

    RhnSystemDetails systemDetails = new RhnSystemDetails();
    systemDetails.setCompanyId(123l);
    when(rhnSystemDetailsRepository.findRhnSystemDetailsByInstanceId(kernelVersion.getInstanceId())).thenReturn(
            systemDetails);
    complianceRepositoryImpl.updateKernelVersion(kernelVersion);
    KernelVersion emptyKernalVersion = new KernelVersion();
    complianceRepositoryImpl.updateKernelVersion(emptyKernalVersion);
}
 
Example 16
@Before
public void individualTestSetup() throws IOException {
  // Wiremock stubs
  stubFor(
      post("/session")
          .willReturn(
              ok(
                  "{\"value\":{\"capabilities\":{\"desired\":{\"platformName\":\"android\",\"app\":\"test.apk\",\"appActivity\":\"test\",\"appPackage\":\"test\"},\"platformName\":\"android\",\"app\":\"test.apk\",\"appActivity\":\"test\",\"appPackage\":\"test\",\"deviceName\":\"Google Pixel\"},\"sessionId\":\"sessionId\"}}")));
  stubFor(post("/upload").willReturn(ok("{app_url : \"test.apk\"}")));

  // Spring config values
  ReflectionTestUtils.setField(target, "username", "user");
  ReflectionTestUtils.setField(target, "accessKey", "key");
  ReflectionTestUtils.setField(
      target,
      "appPath",
      new DefaultResourceLoader().getResource("test.apk").getFile().getAbsolutePath());
  ReflectionTestUtils.setField(
      target, "uploadPath", "http://localhost:" + wireMockPort + "/upload");

  // Mock URL builder
  BrowserStackUrlBuilder mockUrlBuilder = mock(BrowserStackUrlBuilder.class);
  when(mockUrlBuilder.buildBrowserStackUrl(anyString(), anyString()))
      .thenReturn(new URL("http://localhost:" + wireMockPort));
  ReflectionTestUtils.setField(target, "browserStackUrlBuilder", mockUrlBuilder);
}
 
Example 17
Source Project: sdn-rx   Source File: Neo4jDataAutoConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("…should create new Neo4j Template")
void shouldCreateNew() {
	contextRunner
		.withUserConfiguration(ConfigurationWithExistingDatabaseSelectionProvider.class)
		.run(ctx -> {
			assertThat(ctx).hasSingleBean(Neo4jTemplate.class);

			// Verify that the template uses the provided database name provider
			Neo4jTemplate template = ctx.getBean(Neo4jTemplate.class);
			DatabaseSelectionProvider provider = (DatabaseSelectionProvider) ReflectionTestUtils
				.getField(template, "databaseSelectionProvider");
			assertThat(provider).isSameAs(ctx.getBean(DatabaseSelectionProvider.class));
		});
}
 
Example 18
Source Project: pacbot   Source File: VulnerabilityRepositoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getTrendAnnotationsTest_Exception() throws Exception {

	mockStatic(PacHttpUtils.class);
	when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenThrow(new Exception());
	ReflectionTestUtils.setField(vulnerabilityRepository, "esUrl", "dummyEsURL");

	assertTrue(vulnerabilityRepository.getTrendAnnotations("ag", new Date()).size() == 0);
}
 
Example 19
Source Project: gpmr   Source File: UserResourceIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    UserResource userResource = new UserResource();
    ReflectionTestUtils.setField(userResource, "userRepository", userRepository);
    ReflectionTestUtils.setField(userResource, "userService", userService);
    this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource).build();
}
 
Example 20
@Test
void shouldWriteDynamicRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithStringlyTypedRelatives newPerson = new PersonWithStringlyTypedRelatives("Test");
	Map<String, Person> relatives = newPerson.getRelatives();

	Person d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R1");
	relatives.put("RELATIVE_1", d);

	d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R2");
	relatives.put("RELATIVE_2", d);

	newPerson = repository.save(newPerson);
	relatives = newPerson.getRelatives();
	assertThat(relatives).containsOnlyKeys("RELATIVE_1", "RELATIVE_2");

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
			+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
			+ "RETURN size((t)-->(:Person))"
			+ " as numberOfRelations", Values.parameters("id", newPerson.getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(2L);
	}
}
 
Example 21
Source Project: pacbot   Source File: VulnerabilityRepositoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getVulnerabilityByQidTest() throws Exception {

	String response = "{\"hits\":{\"total\":68,\"hits\":[{\"_index\":\"qualys-kb\",\"_type\":\"kb\",\"_id\":\"236591\",\"_score\":8.899231,"
			+ "\"_source\":{\"qid\":\"236591\",\"vulntype\":\"Vulnerability\",\"severitylevel\":4,\"title\":\"Red Hat Update for kernel\","
			+ "\"category\":\"RedHat\",\"lastservicemodificationdatetime\":\"2018-05-29T20:32:16z\",\"publisheddatetime\":\"2018-01-04T04:02:43z\","
			+ "\"_loadDate\":\"2018-07-09T14:23:27z\",\"latest\":true,\"classification\":\"OS\"}}]}}";

	mockStatic(PacHttpUtils.class);
	when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenReturn(response);
	ReflectionTestUtils.setField(vulnerabilityRepository, "esUrl", "dummyEsURL");

	assertThat(vulnerabilityRepository.getVulnerabilityByQid("qid"), is(notNullValue()));
}
 
Example 22
@Test
public void testUndertowHttp2Enabled() {
    props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
    UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
    webConfigurer.customize(container);
    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
 
Example 23
@Test
public void testUndertowHttp2Enabled() {
    props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
    UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
    webConfigurer.customize(container);
    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
 
Example 24
Source Project: pacbot   Source File: CertificateRepositoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getCerticatesExpiryByApplicationTest_Exception() throws Exception {
    
    mockStatic(PacHttpUtils.class);
    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenThrow(new Exception());
    ReflectionTestUtils.setField(certificateRepository, "esUrl", "dummyEsURL");
    
    assertThatThrownBy(() -> certificateRepository.getCertificatesExpiryByApplication("ag"))
    .isInstanceOf(DataException.class);
}
 
Example 25
@Test
void shouldWriteDynamicRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithStringlyTypedRelatives newPerson = new PersonWithStringlyTypedRelatives("Test");
	Person d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R1");
	newPerson.getRelatives().put("RELATIVE_1", d);
	d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R2");
	newPerson.getRelatives().put("RELATIVE_2", d);

	List<PersonWithStringlyTypedRelatives> recorded = new ArrayList<>();
	repository.save(newPerson)
		.as(StepVerifier::create)
		.recordWith(() -> recorded)
		.consumeNextWith(personWithRelatives -> {
			Map<String, Person> relatives = personWithRelatives.getRelatives();
			assertThat(relatives).containsOnlyKeys("RELATIVE_1", "RELATIVE_2");
		})
		.verifyComplete();

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
				+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
				+ "RETURN size((t)-->(:Person))"
				+ " as numberOfRelations",
			Values.parameters("id", recorded.get(0).getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(2L);
	}
}
 
Example 26
@Before
public void setup() {
    JHipsterProperties jHipsterProperties = new JHipsterProperties();
    tokenProvider = new TokenProvider(jHipsterProperties);
    ReflectionTestUtils.setField(tokenProvider, "secretKey", "test secret");
    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
    jwtFilter = new JWTFilter(tokenProvider);
    SecurityContextHolder.getContext().setAuthentication(null);
}
 
Example 27
@Before
public void init() {
  hiveConf.setVar(ConfVars.METASTOREURIS, "thrift://localhost:123");
  client = new ThriftMetastoreClientManager(hiveConf, hiveCompatibleThriftHiveMetastoreIfaceFactory,
      connectionTimeout);
  ReflectionTestUtils.setField(client, "transport", transport);
  ReflectionTestUtils.setField(client, "isConnected", true);
}
 
Example 28
Source Project: spring-analysis-note   Source File: LruContextCacheTests.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void assertCacheContents(DefaultContextCache cache, String... expectedNames) {

	Map<MergedContextConfiguration, ApplicationContext> contextMap =
			(Map<MergedContextConfiguration, ApplicationContext>) ReflectionTestUtils.getField(cache, "contextMap");

	// @formatter:off
	List<String> actualNames = contextMap.keySet().stream()
		.map(cfg -> cfg.getClasses()[0])
		.map(Class::getSimpleName)
		.collect(toList());
	// @formatter:on

	assertEquals(asList(expectedNames), actualNames);
}
 
Example 29
Source Project: e-commerce-microservice   Source File: WebConfigurerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUndertowHttp2Enabled() {
    props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
    UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
    webConfigurer.customize(container);
    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
 
Example 30
Source Project: pmq   Source File: AuditLogServiceImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void insertTest() {
	AuditLogServiceImpl auditLogServiceImpl=new AuditLogServiceImpl();
	UserInfoHolder userInfoHolder=mock(UserInfoHolder.class);
	AuditLogRepository auditLogRepository=mock(AuditLogRepository.class);
	ReflectionTestUtils.setField(auditLogServiceImpl, "userInfoHolder", userInfoHolder);
	ReflectionTestUtils.setField(auditLogServiceImpl, "auditLogRepository", auditLogRepository);
	auditLogServiceImpl.init();
	AuditLogEntity entity=new AuditLogEntity();
	entity.setContent("test");
	entity.setId(1L);
	entity.setRefId(1L);
	auditLogServiceImpl.insert(entity);
	verify(auditLogRepository).insert(entity);
}