0

I am writing unit test cases for Controller layer. I have a call where i am getting user from Spring SecurityContextHolder. When i run my test case i get Null pointer exception because I don't know how to mock Spring security context.

Below is my code, any suggestion how to do it?

Controller Methhod:

@RequestMapping(method = RequestMethod.POST)
public void saveSettings(@RequestBody EmailSettingDTO emailSetting) {
    User user = ((CurrentUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser();
    settings.saveUserEmailSetting(user, emailSetting);

}

My Test case :

@Test  public void testSaveSettings() throws Exception {
mockMvc.perform(post(BASE_URL).content(this.objectMapper.writeValueAsString(emailDto))
  .contentType(MediaTypes.HAL_JSON)).andExpect(status().isOk());

}

Sohaib Yasir
  • 41
  • 1
  • 5

2 Answers2

0

There is a Spring Security Test library for this purpose.

You can use @WithMockUser to achieve this. See the post

shazin
  • 21,379
  • 3
  • 54
  • 71
0

You can use @WithUserDetails

this annotation can be added to a test method to emulate running with a UserDetails returned from the UserDetailsService.

By using this, you create a context to run a test in, for example:

@Test
@WithUserDetails("admin")
public void testAdmin() throws Exception {
    mockMvc.perform(...);
}

This will execute testAdmin() with the SecurityContext of admin.

But please note, in order to use this; there must be a User persisted with the name admin, otherwise you will get result exceptions.

px06
  • 2,256
  • 1
  • 27
  • 47