Inject @AuthenticationPrincipal when unit testing a Spring REST controller

后端 未结 4 1649
不知归路
不知归路 2021-01-03 23:04

I am having trouble trying to test a REST endpoint that receives an UserDetails as a parameter annotated with @AuthenticationPrincipal.

It

4条回答
  •  情话喂你
    2021-01-03 23:34

    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.

提交回复
热议问题