0

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).

Vinutha
  • 41
  • 9
  • 1
    If it really is a plain unit test it should work, you are probably writing an integration test using `MockMvc` for which you have to provide proper authentication information. – M. Deinum Jun 27 '22 at 12:05

1 Answers1

2

You can annotate your test method with @WithMockUser (available since spring 4.0) e.g. @WithMockUser(roles = "MANAGER")

@Test
@WithMockUser(username = "myuser", password = "pass", roles = "USER")
public void test() throws Exception {
    mockMvc.perform(get("/foo"))
        .andExpect(status().isOk());
}

Remember to add the following dependency to test the dependencies of your project:

org.springframework.security:spring-security-test

Viktar Patotski
  • 584
  • 6
  • 20
timguy
  • 2,063
  • 2
  • 21
  • 40
  • We have annotated the class with AutoConfigureMockMvc and autowired MockMvc but getting NullPointerException : mockMvc is null. – Vinutha Jun 27 '22 at 14:57
  • maybe this could help? https://stackoverflow.com/questions/59534247/spring-boot-mvc-test-mockmvc-is-always-null – timguy Jun 28 '22 at 08:06