I am having trouble trying to test a REST endpoint that receives an UserDetails
as a parameter annotated with @AuthenticationPrincipal.
It
This can be done by injection a HandlerMethodArgumentResolver
into your Mock MVC context or standalone setup. Assuming your @AuthenticationPrincipal
is of type ParticipantDetails
:
private HandlerMethodArgumentResolver putAuthenticationPrincipal = new HandlerMethodArgumentResolver() {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().isAssignableFrom(ParticipantDetails.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
return new ParticipantDetails(…);
}
};
This argument resolver can handle the type ParticipantDetails
and just creates it out of thin air, but you see you get a lot of context. Later on, this argument resolver is attached to the mock MVC object:
@BeforeMethod
public void beforeMethod() {
mockMvc = MockMvcBuilders
.standaloneSetup(…)
.setCustomArgumentResolvers(putAuthenticationPrincipal)
.build();
}
This will result in your @AuthenticationPrincipal
annotated method arguments to be populated with the details from your resolver.