@WithMockUser 테스트 시 getPrincipal Null 해결

문제 상황 테스트 코드를 작성할 때 Security에서 제공하는 @WithMockUser 어노테이션을 사용해서 인증 테스트를 수행했습니다. 하지만 Authentication의 getPrincipal() 메소드를 사용할 때 null이 반환되는 현상이 발생해서 테스트를 통과하지 못했습니다. 기존의 방식 @GetMapping("/mycomments") public Response<Page<CommentResponse>> getMyComments(Authentication authentication, Pageable pageable) { String username = authentication.getName(); Page<CommentResponse> response = postService.getMyComments(username, pageable).map(CommentResponse::fromComment); return Response.success(response); } authentication 클래스에서 getName()을 통해 서비스단에 유저의 이름을 전달하는 로직이었습니다. 테스트 코드 @Test @WithMockUser(username = "username") @DisplayName("내 댓글 조회 성공") void 내_댓글_조회_성공() throws Exception { //Given String username = "username"; //When when(postService.getMyComments(eq(username), any(Pageable.class))).thenReturn(Page.empty()); //Then mvc.perform(get("/api/v1/post/mycomments")) .andExpect(status().isOk()); } 기존의 authentication.getName() 메소드를 사용할 때는 정상적으로 통과하는 것을 볼 수 있습니다. ...

May 2, 2023 · Lee WooJin