Java Code Examples for org.springframework.test.util.ReflectionTestUtils#setField()

The following examples show how to use org.springframework.test.util.ReflectionTestUtils#setField() . 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: PropertyConfigOverridePolicyTest.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
private void addDbaOverrides(){
    Map<String, Map<String, Integer>> mockDbaPolicy = new HashMap<>();
    Map<String, Integer> mockDba = new HashMap<>();
    mockDba.put("dev", DBA_DBA_OVERRIDE);
    Map<String, Integer> mockDatafix = new HashMap<>();
    mockDatafix.put("dev", DBA_DATAFIX_OVERRIDE);
    Map<String, Integer> mockReadonly = new HashMap<>();
    mockReadonly.put("dev", DBA_READONLY_OVERRIDE);

    mockDbaPolicy.put(DBA_ROLE, mockDba);
    mockDbaPolicy.put(DATAFIX_ROLE, mockDatafix);
    mockDbaPolicy.put(READONLY_ROLE, mockReadonly);

    mockOverrides.put("dba", mockDbaPolicy);
    ReflectionTestUtils.setField(overridePolicy,"overrides", mockOverrides);
}
 
Example 2
Source File: DynamicRelationshipsIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUpdateDynamicRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithRelatives person = repository.findById(idOfExistingPerson).get();
	assumeThat(person).isNotNull();
	assumeThat(person.getName()).isEqualTo("A");

	Map<TypeOfRelative, Person> relatives = person.getRelatives();
	assumeThat(relatives).containsOnlyKeys(TypeOfRelative.HAS_WIFE, TypeOfRelative.HAS_DAUGHTER);

	relatives.remove(TypeOfRelative.HAS_WIFE);
	Person d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "D");
	relatives.put(TypeOfRelative.HAS_SON, d);
	ReflectionTestUtils.setField(relatives.get(TypeOfRelative.HAS_DAUGHTER), "firstName", "C2");

	person = repository.save(person);
	relatives = person.getRelatives();
	assertThat(relatives).containsOnlyKeys(TypeOfRelative.HAS_DAUGHTER, TypeOfRelative.HAS_SON);
	assertThat(relatives.get(TypeOfRelative.HAS_DAUGHTER).getFirstName()).isEqualTo("C2");
	assertThat(relatives.get(TypeOfRelative.HAS_SON).getFirstName()).isEqualTo("D");
}
 
Example 3
Source File: AssetRepositoryTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Test
public void testgetNotificationDetails() throws Exception {
    Map<String, Object> phd1 = new HashMap<>();
    phd1.put("_resourceid", "a1");
    phd1.put("open", "p1");

    Map<String, Object> phd2 = new HashMap<>();
    phd2.put("_resourceid", "b2");
    phd1.put("closed", "p2");

    List<Map<String, Object>> phdList = new ArrayList<>();
    phdList.add(phd1);
    phdList.add(phd2);
    when(elasticSearchRepository.getDataFromESBySize(anyObject(), anyObject(), anyObject(), anyObject(),
            anyObject(), anyObject(), anyInt(), anyInt(), anyObject(), anyObject())).thenReturn(phdList);
    ReflectionTestUtils.setField(repository, "esRepository", elasticSearchRepository);
    List<Map<String, Object>> a = repository.getNotificationDetails("a1", null, "");
    assertTrue(a.size() == 2);
}
 
Example 4
Source File: AssetServiceTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Test
public void testgetEc2CreatorDetail() throws Exception{
    Map<String, Object> ec2Resource = new HashMap<>();
    ec2Resource.put("statename", "state1");
    ec2Resource.put("createdBy", "value");
    ec2Resource.put("creationDate", "value");
    ec2Resource.put("email", "value");

    
    when(assetRepository.getResourceCreateInfo(anyObject())).thenReturn(ec2Resource);
    ReflectionTestUtils.setField(service, "repository", assetRepository);
    
    
    Map<String, Object> a = service.getEc2CreatorDetail("a1");
    assertTrue(a.size()==4);
}
 
Example 5
Source File: TaggingRepositoryImplTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Test
public void getUntaggedTargetTypeIssuesTest() throws Exception {
    String response = "{\"count\":239,\"_shards\":{\"total\":176,\"successful\":176,\"skipped\":0,\"failed\":0}}";
    mockStatic(PacHttpUtils.class);
    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenReturn(response);
    ReflectionTestUtils.setField(taggingRepositoryImpl, "esUrl", "dummyEsURL");
    UntaggedTargetTypeRequest request = new UntaggedTargetTypeRequest();
    request.setAg("aws-all");
    List<String> tagList = new ArrayList<>();
    tagList.add("tag1");
    tagList.add("tag2");
    assertThat(taggingRepositoryImpl.getUntaggedTargetTypeIssues(request, tagList), is(notNullValue()));
    tagList = new ArrayList<>();
    // check Tags list empty scenario
    assertThat(taggingRepositoryImpl.getUntaggedTargetTypeIssues(request, tagList), is(notNullValue()));
    // check throws DataException
    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenThrow(new DataException());
    List<String> tagListfinal = new ArrayList<>();
    assertThatThrownBy(() -> taggingRepositoryImpl.getUntaggedTargetTypeIssues(request, tagListfinal))
            .isInstanceOf(DataException.class);

}
 
Example 6
Source File: AssetDetailControllerTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Test
public void testgetEc2ResourceSummary() throws Exception {
    List<Map<String, Object>> ec2List = new ArrayList<>();
    Map<String, Object> ec2Map = new HashMap<>();
    ec2Map.put("resourceid", "x");
    ec2Map.put("ipaddress", "y");
    ec2List.add(ec2Map);
    when(service.getEC2AvgAndTotalCost(anyString())).thenReturn(ec2Map);

    ReflectionTestUtils.setField(controller, "assetService", service);
    ResponseEntity<Object> responseObj1 = controller.getEc2ResourceSummary("a1");
    assertTrue(responseObj1.getStatusCode() == HttpStatus.OK);
    assertTrue(((Map<String, Object>) responseObj1.getBody()).get("data") != null);

    doThrow(new NullPointerException()).when(service).getEC2AvgAndTotalCost(anyString());
    ReflectionTestUtils.setField(controller, "assetService", service);

    ResponseEntity<Object> responseObj2 = controller.getEc2ResourceSummary("a1");
    assertTrue(responseObj2.getStatusCode() == HttpStatus.OK);

}
 
Example 7
Source File: AssetDetailControllerTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Test
public void testgetDiskUtilizationByInstanceId() throws Exception {
    List<Map<String, Object>> utilList = new ArrayList<>();
    Map<String, Object> utilMap = new HashMap<>();
    utilMap.put("date", "d1");
    utilMap.put("disk-utilization", 50);
    utilList.add(utilMap);

    when(service.getInstanceDiskUtilization(anyObject())).thenReturn(utilList);
    ReflectionTestUtils.setField(controller, "assetService", service);

    ResponseEntity<Object> responseObj1 = controller.getDiskUtilizationByInstanceId("");
    assertTrue(responseObj1.getStatusCode() == HttpStatus.EXPECTATION_FAILED);

    ReflectionTestUtils.setField(controller, "qualysEnabled", true);
    ResponseEntity<Object> responseObj2 = controller.getDiskUtilizationByInstanceId("a1");
    assertTrue(responseObj2.getStatusCode() == HttpStatus.OK);
    assertTrue(((Map<String, Object>) responseObj2.getBody()).get("data") != null);

    doThrow(new DataException()).when(service).getInstanceDiskUtilization(anyObject());
    ReflectionTestUtils.setField(controller, "assetService", service);
    ResponseEntity<Object> responseObj0 = controller.getDiskUtilizationByInstanceId("a1");
    assertTrue(responseObj0.getStatusCode() == HttpStatus.EXPECTATION_FAILED);
}
 
Example 8
Source File: TokenProviderTest.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    tokenProvider = new TokenProvider( new JHipsterProperties());
    key = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));

    ReflectionTestUtils.setField(tokenProvider, "key", key);
    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
}
 
Example 9
Source File: TokenProviderTest.java    From flair-engine with Apache License 2.0 5 votes vote down vote up
@Test
public void testReturnFalseWhenJWTisExpired() {
    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", -ONE_MINUTE);

    Authentication authentication = createAuthentication();
    String token = tokenProvider.createToken(authentication, false);

    boolean isTokenValid = tokenProvider.validateToken(token);

    assertThat(isTokenValid).isEqualTo(false);
}
 
Example 10
Source File: VulnerabilityRepositoryTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Test
public void getUniqueAppTest() throws Exception {

	String response = "{\"aggregations\":{\"severity\":{\"buckets\":{\"S3\":{\"doc_count\":871,\"NAME\":{\"value\":1}},"
			+ "\"S4\":{\"doc_count\":871,\"NAME\":{\"value\":1}},\"S5\":{\"doc_count\":844,\"NAME\":{\"value\":1}}}}}}";

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

	assertTrue(vulnerabilityRepository.getUniqueApp("ag").size() == 3);
}
 
Example 11
Source File: AssetRepositoryTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Test
public void testgetAdGroupDetails() throws Exception {
    Map<String, Object> adMap1 = new HashMap<>();
    adMap1.put("admin", "a1");

    Map<String, Object> adMap2 = new HashMap<>();
    adMap2.put("admin", "b2");

    List<Map<String, Object>> adList = new ArrayList<>();
    adList.add(adMap1);
    adList.add(adMap2);

    boolean isDataExceptionThrown = false;
    try {
        repository.getAdGroupDetails();
    } catch (DataException e) {
        isDataExceptionThrown = true;
    }
    assertTrue(isDataExceptionThrown);

    when(elasticSearchRepository.getDataFromES(anyObject(), anyObject(), anyObject(), anyObject(), anyObject(),
            anyObject(), anyObject())).thenReturn(adList);
    ReflectionTestUtils.setField(repository, "esRepository", elasticSearchRepository);

    List<Map<String, Object>> result = repository.getAdGroupDetails();
    assertTrue(result.size() > 0);
}
 
Example 12
Source File: TaggingServiceImplTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Test
public void getUntaggingByTargetTypesTestExeptions() throws Exception {
    //test serviceException when targetTypes empty
    List<Map<String, Object>>  emptyList = new ArrayList<>();
    when(repository.getRuleTargetTypesFromDbByPolicyId(anyString()))
    .thenReturn(emptyList);
    ReflectionTestUtils.setField(taggingServiceImpl, "mandatoryTags",
            "Application,Environment");
    assertThatThrownBy(() -> taggingServiceImpl
            .getUntaggingByTargetTypes(untaggedTargetTypeRequest))
    .isInstanceOf(ServiceException.class);
}
 
Example 13
Source File: RecommendationsControllerTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Test
public void getSummaryByApplicationTest() throws Exception {
	
	when(recommendationsService.getSummaryByApplication(anyString(),anyString())).thenReturn(new HashMap<>());
	ReflectionTestUtils.setField(recommendationsController, "recommendationsService", recommendationsService);
	assertTrue(recommendationsController.getSummaryByApplication("ag", "app").getStatusCode() == HttpStatus.OK);
	
	when(recommendationsService.getSummaryByApplication(anyString(),anyString())).thenThrow(new DataException());
	assertTrue(recommendationsController.getSummaryByApplication("ag", "app").getStatusCode() == HttpStatus.EXPECTATION_FAILED);
}
 
Example 14
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 15
Source File: AbstractTest.java    From pmq with Apache License 2.0 5 votes vote down vote up
public void init() {
	soaConfig = new SoaConfig();
	Environment env = mock(Environment.class);
	ReflectionTestUtils.setField(soaConfig, "env", env);
	when(env.getProperty(anyString(), anyString())).thenAnswer(new Answer<String>() {
		@Override
		public String answer(InvocationOnMock invocation) throws Throwable {
			Object[] args = invocation.getArguments();
			if(propertyMap.containsKey(args[0])) {
				return propertyMap.get(args[0]);
			}
			return (String) args[1];
		}
	});		
}
 
Example 16
Source File: UserResourceIntTest.java    From klask-io with GNU General Public License v3.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 17
Source File: CreateAccountCmdTest.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecuteWithEmptyPassword() {
    ReflectionTestUtils.setField(createAccountCmd, "password", "");
    try {
        createAccountCmd.execute();
        Assert.fail("should throw exception for a empty password");
    } catch (final ServerApiException e) {
        Assert.assertEquals(ApiErrorCode.PARAM_ERROR, e.getErrorCode());
        Assert.assertEquals("Empty passwords are not allowed", e.getMessage());
    }
    Mockito.verify(accountService, Mockito.never()).createUserAccount(null, null, null, null, null, null, null, accountType, domainId, null, null, null, null);
}
 
Example 18
Source File: MqFilterTest.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Test
public void doFilterTest() throws IOException, ServletException {
	StatService statService=mock(StatService.class);
	MqFilter mqFilter=new MqFilter();
	ReflectionTestUtils.setField(mqFilter, "statService", statService);
	
	ServletRequest servletRequest=mock(ServletRequest.class);
	ServletResponse servletResponse=mock(ServletResponse.class);
	FilterChain filterChain=mock(FilterChain.class);			
	mqFilter.doFilter(servletRequest, servletResponse, filterChain);
	//verify(filterChain).doFilter(eq(servletRequest), eq(servletResponse));
	verify(filterChain).doFilter(servletRequest, servletResponse);
}
 
Example 19
Source File: AssetDetailControllerTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Test
public void testgetOpenPortsByInstanceId() throws Exception {
    List<Map<String, Object>> softwareList = new ArrayList<>();

    when(service.getInstanceSoftwareInstallDetails(anyObject(), anyObject(), anyObject(), anyObject()))
            .thenReturn(softwareList);
    ReflectionTestUtils.setField(controller, "assetService", service);
    ResponseEntity<Object> responseObj0 = controller.getOpenPortsByInstanceId("a1", 1, 1, "pacman");
    assertTrue(responseObj0.getStatusCode() == HttpStatus.EXPECTATION_FAILED);

    Map<String, Object> softwareMap1 = new HashMap<>();
    softwareMap1.put("name", "x");
    softwareMap1.put("value", "y");
    Map<String, Object> softwareMap2 = new HashMap<>();
    softwareMap2.put("name", "p");
    softwareMap2.put("value", "q");
    softwareList.add(softwareMap2);
    Map<String, Object> softwareMap3 = new HashMap<>();
    softwareMap3.put("name", "a");
    softwareMap3.put("value", "b");
    softwareList.add(softwareMap3);

    when(service.getOpenPortDetails(anyObject(), anyObject(), anyObject(), anyObject())).thenReturn(softwareList);
    ReflectionTestUtils.setField(controller, "assetService", service);
    ReflectionTestUtils.setField(controller, "qualysEnabled", true);

    ResponseEntity<Object> responseObj1 = controller.getOpenPortsByInstanceId("a1", 0, 1, "pacman");
    assertTrue(responseObj1.getStatusCode() == HttpStatus.OK);
    assertTrue(((Map<String, Object>) responseObj1.getBody()).get("data") != null);

    ResponseEntity<Object> responseObj2 = controller.getOpenPortsByInstanceId("a1", 1, 1, "pacman");
    assertTrue(responseObj2.getStatusCode() == HttpStatus.OK);
    assertTrue(((Map<String, Object>) responseObj2.getBody()).get("data") != null);

    ResponseEntity<Object> responseObj3 = controller.getOpenPortsByInstanceId("a1", 6, 1, "pacman");
    assertTrue(responseObj3.getStatusCode() == HttpStatus.EXPECTATION_FAILED);

    ResponseEntity<Object> responseObj4 = controller.getOpenPortsByInstanceId("", 1, 1, "pacman");
    assertTrue(responseObj4.getStatusCode() == HttpStatus.EXPECTATION_FAILED);

    ResponseEntity<Object> responseObj5 = controller.getOpenPortsByInstanceId("a1", 1, 8, "pacman");
    assertTrue(responseObj5.getStatusCode() == HttpStatus.OK);

    ResponseEntity<Object> responseObj6 = controller.getOpenPortsByInstanceId("a1", 0, 0, "pacman");
    assertTrue(responseObj6.getStatusCode() == HttpStatus.OK);

    ResponseEntity<Object> responseObj7 = controller.getOpenPortsByInstanceId("a1", null, 0, "pacman");
    assertTrue(responseObj7.getStatusCode() == HttpStatus.OK);
}
 
Example 20
Source File: ConfigServiceTest.java    From apollo with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() {
  ReflectionTestUtils.setField(configService, "propertyResolver", resolver);
}