[Java Spring] @PreAuthorize는 Spring Security 테스트코드관련 어노테이션이 아닙니다

김태훈·2023년 9월 3일
0
post-thumbnail

@PreAuthorize 로 인증된 UserDetails 정보로 가정하고 테스트코드 작성

    @Test
    @PreAuthorize("authenticated")
    @DisplayName("올바른 댓글 형식에서의 댓글 저장")
    void createValidComment(){
        Comment comment = new Comment(1L,
                new MemberProfileEntity("test_image_path","test_nickname","test_introduce","test_tag"),
                Date.valueOf(now()),
                null,
                new CommentSaveDto(PostType.MEMO,1L,"comment_text"));
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        System.out.println("authentication = " + authentication);
        assertEquals(commentRepository.createComment(comment),2);
    }

이렇게 하면 authentication이 null이 나온다.
근데 당연한것이,
현재 test code를 실행중이기 때문에,
메서드에 @ExtendWith(SpringExtension.class)를 붙여야만 실행 된다. 바보같았다
-> 엥 그래도 안되네..? 한가지 부족했다.

아래 공식문서를 보자.

https://docs.spring.io/spring-security/reference/servlet/test/method.html

위에 Security Test SetUp 을 보면 두가지가 필요하다.

  1. @ExtendWith
    해당 어노테이션은 Application Context를 사용할 수 있는 spring-test-module 을 만든다.
  2. @ContextConfiguration
    위 어노테이션은 ApplicationContext를 만들고, 사용하기 위한 spring-test 설정 정보를 만든다.

이렇게 해도 안되길래 찾아봤는데..

알고보니 @PreAuthorize는 테스트코드에서 사용하는 것이 아니었다 ㅎㅎ. 오해!

@WithMockUser 로 바꿉시다.

    @Test
    @WithMockUser
    @DisplayName("올바른 댓글 형식에서의 댓글 저장")
    void createValidComment(){
        Comment comment = new Comment(1L,
                new MemberProfileEntity("test_image_path","test_nickname","test_introduce","test_tag"),
                Date.valueOf(now()),
                null,
                new CommentSaveDto(PostType.MEMO,1L,"comment_text"));
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        System.out.println("authentication = " + authentication);
        assertEquals(commentRepository.createComment(comment),2);
    }

당신이 찾는 모든 Spring Security 관련 테스트코드는 여기에 다 있다.
https://docs.spring.io/spring-security/reference/servlet/test/method.html

profile
기록하고, 공유합시다

0개의 댓글