This is a continuation of this question Spring WebMvcTest how to mock Authentication?
I'm trying to test a controller method in Spring-boot that receives an Authentication object as parameter. The controller is a RestController with @CrossOrigin annotation. The method looks like this:
@GetMapping("/authentication")
public String testAuthentication(Authentication authentication) {
UserDetailsStub userDetailsStub = (UserDetailsStub) authentication.getPrincipal();
return userDetailsStub.getUsername();
}
As you can see i get the principal from the Authentication out of the parameters.
The problem is, in my WebMvcTest test case i get a NullPointerException because in the test case, authentication seems to be null. My question is why?
I have tried adding a given call which will return a custom UserDetails object in a @PostConstruct annotated metho in the test case, but still i get the NullPointerException.
My test case looks like this:
@Import(SecurityConfiguration.class)
@RunWith(SpringRunner.class)
@WebMvcTest(PDPController.class)
@AutoConfigureMockMvc(addFilters = false)
public class PDPControllerTests {
@Autowired
private MockMvc mvc;
@MockBean(name = "userDetailsService")
private MyUserDetailsService userDetailsService;
//..
@PostConstruct
public void setup() {
given(userDetailsService.loadUserByUsername(anyString()))
.willReturn(new UserDetailsStub());
}
//..
@Test
@WithUserDetails(value = "username", userDetailsServiceBeanName = "userDetailsService")
public void testAuthentication() throws Exception {
mvc.perform(get("/pdps/authentication").secure(true)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
Why is authentication null in the test case, even when i supply it in the @PostConstruct method?
A GitHub project with minimal code that reproduces the error can be found here. https://github.com/Kars1090/SpringSecurityTest
Thanks!