Inject @AuthenticationPrincipal when unit testing a Spring REST controller

后端 未结 4 1774
不知归路
不知归路 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

    I know the question is old but for folks still looking, what worked for me to write a Spring Boot test with @AuthenticationPrincipal (and this may not work with all instances), was annotating the test @WithMockUser("testuser1")

    @Test
    @WithMockUser("testuser1")
    public void successfullyMockUser throws Exception {
        mvc.perform(...));
    }
    

    Here is a link to the Spring documentation on @WithMockUser

提交回复
热议问题