강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Không có người viết

Bài viết có thông tin người viết đã bị xóa.

Chương trình phát triển hài hước của Hodolman (SpringBoot, Vue.JS, AWS)

총합 kiểm thử Security Custom WithMockUser

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

Viết

·

250

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());
    }
vue.jsawsspring-bootjpaspring-security

Câu trả lời 1

0

안녕하세요, 인프런 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

Không có người viết

Bài viết có thông tin người viết đã bị xóa.

Đặt câu hỏi