samedi 20 décembre 2014

NullPointerException while unit testing spring security application

I am new to spring security. I am working on unit testing an application, which uses the following method call at some point in execution.



public static List<String> getUserDetails() {
List<String> currentUserDetails = new ArrayList<String>();
CurrentUser currentUser = (CurrentUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
currentUserDetails.add(0, currentUser.getUsername());//currentUser is null
currentUserDetails.add(1, currentUser.getOrg_name());
currentUserDetails.add(2, currentUser.getPassword());
return currentUserDetails;
}


Here the currentUser is a org.springframework.security.core.userdetails.User. After having looked at the SO question I tried this in my unit test to set a user.



@Test
public void testMyMethod() throws Exception {

Authentication authentication = Mockito.mock(Authentication.class);
// Mockito.whens() for your authorization object

SecurityContext securityContext = Mockito.mock(SecurityContext.class);
when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
assertNotNull(("Should not be null"), new MyObject().myMethod());
}


The security part of the code is not written by me. So, because of this issue I am not able to unit test my modules.


Aucun commentaire:

Enregistrer un commentaire