org.springframework.test.util.ReflectionTestUtils Java Examples

The following examples show how to use org.springframework.test.util.ReflectionTestUtils. 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: WebConfigurerTest.java    From e-commerce-microservice with 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 File: WebConfigurerTest.java    From jhipster-microservices-example with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@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 File: AccountManagerImplTest.java    From cosmic with 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 #5
Source File: BrowserStackWebDriverBuilderTest.java    From justtestlah with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: EncryptSystemTest.java    From spring-data-mongodb-encrypt with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: AssetServiceTest.java    From pacbot with 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 #8
Source File: ComplianceRepositoryImplTest.java    From pacbot with 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 #9
Source File: AssetControllerTest.java    From pacbot with 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 #10
Source File: OAuth2AutoConfigurationTests.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: KeeperContainerServiceTest.java    From x-pipe with 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 #12
Source File: ConsumerCommitServiceImplTest.java    From pmq with 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 #13
Source File: EncryptSystemTest.java    From spring-data-mongodb-encrypt with Apache License 2.0 6 votes vote down vote up
@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 File: CertificateRepositoryTest.java    From pacbot with 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 #15
Source File: ESManagerTest.java    From pacbot with 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 #16
Source File: AssetListControllerTest.java    From pacbot with 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 #17
Source File: JWTFilterTest.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    JHipsterProperties jHipsterProperties = new JHipsterProperties();
    tokenProvider = new TokenProvider(jHipsterProperties);
    ReflectionTestUtils.setField(tokenProvider, "key",
        Keys.hmacShaKeyFor(Decoders.BASE64
            .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")));

    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
    jwtFilter = new JWTFilter(tokenProvider);
    SecurityContextHolder.getContext().setAuthentication(null);
}
 
Example #18
Source File: AssetGroupExceptionServiceImplTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void createAssetGroupExceptionsTest() throws PacManException, IOException {
	AssetGroupException assetGroupExceptionDetails = buildAssetGroupException();
	when(assetGroupExceptionRepository.save(any(AssetGroupException.class))).thenReturn(assetGroupExceptionDetails);
	ElasticSearchProperty elasticSearchProperty = buildElasticSearchProperty();
    when(config.getElasticSearch()).thenReturn(elasticSearchProperty);
       when(response.getEntity()).thenReturn(null);
       when(restClient.performRequest(anyString(), anyString(), any(Map.class), any(HttpEntity.class),
       Matchers.<Header>anyVararg())).thenReturn(response);
       ReflectionTestUtils.setField(assetGroupExceptionServiceImpl, "restClient", restClient);
       when(sl.getStatusCode()).thenReturn(200);
	    when(response.getStatusLine()).thenReturn(sl);
	assertThat(assetGroupExceptionService.createAssetGroupExceptions(getCreateAssetGroupExceptionDetailsRequest(), "userId123"), is(notNullValue()));
}
 
Example #19
Source File: ComplianceRepositoryImplTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Test
public void revokeAndUpdateIssueDetailsTest() throws Exception {
    List<Map<String, Object>> issueDetails = new ArrayList<>();
    Map<String, Object> issueDetailMap = new HashMap<>();
    issueDetailMap.put("resourceType", "ec2");
    issueDetailMap.put("status", "open");
    issueDetailMap.put("severity", "high");
    issueDetailMap.put(PAC_DS, AWS);
    issueDetailMap.put(PAC_DS, AWS);
    issueDetailMap.put(TYPE, "issue");
    issueDetailMap.put(ES_DOC_ROUTING_KEY, "12345");
    issueDetailMap.put(ES_DOC_PARENT_KEY, "ec2");
    issueDetailMap.put(ES_DOC_ID_KEY, "678");
    issueDetails.add(issueDetailMap);

    IssueResponse issueReason = new IssueResponse();
    issueReason.setExceptionReason("exempted");
    issueReason.setIssueId("1234");
    RuleDetails ruleDetails = new RuleDetails();
    ruleDetails.setRuleId("Kernel Compliance Rule");
    ruleDetails.setReason("kernel Version Non-Compliant");
    when(
            elasticSearchRepository.getSortedDataFromES(anyString(), anyString(), anyObject(), anyObject(),
                    anyObject(), anyObject(), anyObject(), anyObject())).thenReturn(issueDetails);
    when(complianceRepositoryImpl.getExemptedIssueDetails(issueReason.getIssueId())).thenReturn(issueDetails);
    when(
            elasticSearchRepository.updatePartialDataToES(anyString(), anyString(), anyString(), anyString(),
                    anyString(), anyObject())).thenReturn(true);
    ReflectionTestUtils.setField(complianceRepositoryImpl, "esUrl", "dummyEsURL");
    complianceRepositoryImpl.revokeAndUpdateIssueDetails("1234");

}
 
Example #20
Source File: DubboMockServiceTest.java    From dubbo-mock with Apache License 2.0 5 votes vote down vote up
private void mockProtocolConfig() {
    protocolConfig.setId(serviceId);
    protocolConfig.setProtocolName("dubbo");
    protocolConfig.setProtocolPort(8878);
    protocolConfigMapper = mock(ProtocolConfigMapper.class);
    when(protocolConfigMapper.selectByPrimaryKey(serviceId)).thenReturn(protocolConfig);
    ReflectionTestUtils.setField(dubboMockServer, "protocolConfigMapper", protocolConfigMapper);
}
 
Example #21
Source File: ElasticSearchRepositoryTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void getDataFromESBySizeTest() throws Exception {
	final ElasticSearchRepository classUnderTest = PowerMockito.spy(new ElasticSearchRepository());
	ReflectionTestUtils.setField(classUnderTest, "esUrl", "esUrl123");
	mockStatic(StringBuilder.class);
	mockStatic(PacHttpUtils.class);
	String response = "{\"count\":\"123\", \"hits\":{\"total\":1000,\"max_score\":null,\"hits\":[{\"_index\":\"bank\",\"_type\":\"_doc\",\"_id\":\"0\",\"sort\":[0],\"_score\":null,\"_source\":{\"account_number\":0,\"balance\":16623,\"firstname\":\"Bradshaw\",\"lastname\":\"Mckenzie\",\"age\":29,\"gender\":\"F\",\"address\":\"244 Columbus Place\",\"employer\":\"Euron\",\"email\":\"[email protected]\",\"city\":\"Hobucken\",\"state\":\"CO\"}}]},\"aggregations\":{\"name\":{\"buckets\":[{\"key\":\"ID\",\"doc_count\":27},{\"key\":\"TX\",\"doc_count\":27}]}}}";
	PowerMockito.when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenReturn(response);

	assertThat(classUnderTest.getDataFromESBySize(eq("dataSource"), eq("targetType"), anyObject(), anyObject(),
			anyObject(), anyObject(), eq(1), eq(1), anyObject(), anyObject()).size(), is(1));

}
 
Example #22
Source File: AssetControllerTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Test
public void testgetResourceCreatedDate() throws Exception {

    AssetUpdateRequest assetUpdateRequest = new AssetUpdateRequest();
    assetUpdateRequest.setAg("ag");
    assetUpdateRequest.setTargettype("targetType");
    assetUpdateRequest.setUpdateBy("update_by");
    assetUpdateRequest.setUpdates(new ArrayList<>());
    assetUpdateRequest.setResources(new HashMap<>());

    when(service.getResourceCreatedDate(anyObject(), anyObject())).thenReturn("01-01-2018");
    ReflectionTestUtils.setField(controller, "assetService", service);

    ResponseEntity<Object> responseObj = controller.getResourceCreatedDate("a1", "ec2");
    assertTrue(responseObj.getStatusCode() == HttpStatus.OK);
    assertTrue(((Map<String, Object>) responseObj.getBody()).get("data").toString().equals("01-01-2018"));
    
    when(service.getResourceCreatedDate(anyObject(), anyObject())).thenReturn("");
    ReflectionTestUtils.setField(controller, "assetService", service);

    ResponseEntity<Object> responseObj1 = controller.getResourceCreatedDate("a1", "ec2");
    assertTrue(responseObj1.getStatusCode() == HttpStatus.EXPECTATION_FAILED);
    
    when(service.getResourceCreatedDate(anyObject(), anyObject())).thenReturn(null);
    ReflectionTestUtils.setField(controller, "assetService", service);

    ResponseEntity<Object> responseObj2 = controller.getResourceCreatedDate("a1", "ec2");
    assertTrue(responseObj2.getStatusCode() == HttpStatus.EXPECTATION_FAILED);
}
 
Example #23
Source File: JWTFilterTest.java    From alchemy with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    JHipsterProperties jHipsterProperties = new JHipsterProperties();
    tokenProvider = new TokenProvider(jHipsterProperties);
    ReflectionTestUtils.setField(tokenProvider, "key",
        Keys.hmacShaKeyFor(Decoders.BASE64
            .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")));

    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
    jwtFilter = new JWTFilter(tokenProvider);
    SecurityContextHolder.getContext().setAuthentication(null);
}
 
Example #24
Source File: ApimlLoggerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testEmpty() {
    ApimlLogger apimlLogger = ApimlLogger.empty();
    Logger logger = (Logger) ReflectionTestUtils.getField(apimlLogger, "logger");
    assertEquals(ApimlLogger.class.getName(), logger.getName());
    assertNull(ReflectionTestUtils.getField(apimlLogger, "messageService"));

    assertNull(apimlLogger.log("someKey"));
}
 
Example #25
Source File: BarResourceIntTest.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void setup() {
    MockitoAnnotations.initMocks(this);
    BarResource barResource = new BarResource();
    ReflectionTestUtils.setField(barResource, "barRepository", barRepository);
    this.restBarMockMvc = MockMvcBuilders.standaloneSetup(barResource)
        .setCustomArgumentResolvers(pageableArgumentResolver)
        .setMessageConverters(jacksonMessageConverter).build();
}
 
Example #26
Source File: EmbeddedCassandraFactoryTests.java    From embedded-cassandra with Apache License 2.0 5 votes vote down vote up
@Test
void getEnvironmentVariables() {
	this.cassandraFactory.getEnvironmentVariables().put("key", "value");
	Cassandra cassandra = this.cassandraFactory.create();
	Object node = ReflectionTestUtils.getField(ReflectionTestUtils.getField(cassandra, "database"), "node");
	Map<String, Object> environmentVariables = (Map<String, Object>) ReflectionTestUtils.getField(node,
			"environmentVariables");
	assertThat(environmentVariables).containsEntry("key", "value");
}
 
Example #27
Source File: UserResourceIntTest.java    From OpenIoE with 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 #28
Source File: DataCounterResourceIntTest.java    From gpmr with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void setup() {
    MockitoAnnotations.initMocks(this);
    DataCounterResource dataCounterResource = new DataCounterResource();
    ReflectionTestUtils.setField(dataCounterResource, "dataCounterRepository", dataCounterRepository);
    this.restDataCounterMockMvc = MockMvcBuilders.standaloneSetup(dataCounterResource)
        .setCustomArgumentResolvers(pageableArgumentResolver)
        .setMessageConverters(jacksonMessageConverter).build();
}
 
Example #29
Source File: VulnerabilityRepositoryTest.java    From pacbot with 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 #30
Source File: LocalDeployerSupportTests.java    From spring-cloud-deployer-local with Apache License 2.0 5 votes vote down vote up
@Test
public void testShutdownPropertyNotConfiguresRequestFactory() throws Exception {
	LocalDeployerProperties properties = new LocalDeployerProperties();
	properties.setShutdownTimeout(-1);
	AbstractLocalDeployerSupport abstractLocalDeployerSupport = new AbstractLocalDeployerSupport(properties) {};
	Object restTemplate = ReflectionTestUtils.getField(abstractLocalDeployerSupport, "restTemplate");
	Object requestFactory = ReflectionTestUtils.getField(restTemplate, "requestFactory");
	Object connectTimeout =  ReflectionTestUtils.getField(requestFactory,"connectTimeout");
	Object readTimeout = ReflectionTestUtils.getField(requestFactory, "readTimeout");
	assertThat(connectTimeout, is(-1));
	assertThat(readTimeout, is(-1));
}