• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

SecurityMockContext 로부터 유저 정보를 가져오기

24.07.05 00:11 작성 조회수 28

0

 @Test
    @DisplayName("글 삭제")
    @CustomMockUser
    void test7() throws Exception {
        // given
        UserPrincipal principal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Member byId = memberRepository.findById(principal.getUserId()).orElseThrow(UserNotFound::new);
        Post post = Post.builder()
                        .title("Hello World")
                        .content("Hello Java")
                        .member(byId)
                        .build();
        postRepository.save(post);

        // expected
        mockMvc.perform(delete("/posts/{postId}", post.getId()))
               .andExpect(status().isOk())
               .andDo(print());
    }

답변 1

답변을 작성해보세요.

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2024.07.07

안녕하세요, 인프런 AI 인턴입니다.
제공해 주신 정보에 따르면, Spring Security를 사용한 테스트 방법에 대해 알고 싶으신 것 같습니다. 테스트에서 특정 사용자의 권한을 가진 상태로 요청을 처리하는 예시는 다음과 같습니다.

Java:

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

@WebMvcTest(UserController.class)
class MySecurityTests {

@Autowired
private MockMvc mvc;

@Test
@WithMockUser(roles = "ADMIN")
void requestProtectedUrlWithUser() throws Exception {
    this.mvc.perform(get("/"));
}

}

Kotlin:

import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders

@WebMvcTest(UserController::class)
class MySecurityTests(@Autowired val mvc: MockMvc) {

@Test
@WithMockUser(roles = ["ADMIN"])
fun requestProtectedUrlWithUser() {
    mvc.perform(MockMvcRequestBuilders.get("/"))
}

}

위 예시에서는 @WithMockUser 어노테이션을 사용하여 테스트를 실행하는 사용자가 ‘ADMIN’ 역할을 가진 것처럼 설정되어 있습니다. 여러분의 테스트에서 @CustomMockUser와 유사한 방법을 사용하고 있다면, @WithMockUser나 Spring Security의 다른 테스트 지원 기능을 사용하여 권한을 설정할 수 있습니다.

더 자세한 내용이나 다른 Spring Security 테스트 관련 기능을 알고 싶으시면, Spring Security의 참조 문서를 확인하세요.

참조 링크: Spring Security reference documentation

채널톡 아이콘