Vinutha
Vinutha

Reputation: 51

How to mock security context holder in spring boot application

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

Upvotes: 0

Views: 949

Answers (1)

timguy
timguy

Reputation: 2582

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

Upvotes: 2

Related Questions