We have below code snippet in our spring boot rest api to get the user role.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_roleName1"))){
// some conditions
} else if (auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_roleName2"))){
// some conditions
}
We have this in one of the test class.
@Before
public void setUp(){
Authentication auth = Mockito.mock(Authentication.class);
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
}
But junit test case is failing. Please suggest how to write junit test case for security context holder (for above mentioned code).