본문 바로가기
Error

@WebMvcTest 403 응답 처리

by YoonJong 2022. 12. 28.
728x90

에러내용

java.lang.AssertionError: Status expected:<201> but was:<403>

에러원인

카테고리 생성에 관련된 controller 테스트 중 403 에러가 발생했다.

해당 컨트롤러는 ADMIN 권한을 가진 사람만 생성할 수 있어서, 아래와 같이 지정해주었는데도 403에러가 발생했다.

@WithMockUser(roles= "ADMIN")

@WebMvcTest 는 슬라이스 테스트로, 모든 사람들이 SecurityConfig 를 필요로 하지 않을 수 있다.따라서, 스프링에서는 사용할 사람은 따로 설정해 사용하라고 한다.

기본 시큐리티 설정으로 되어있어, 따로 시큐리티 설정이 필요했다.

 

에러조치

아래와 같은 Config 파일을 만들어준다.

@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable();

        return http.build();
    }
}

@ImportAutoConfiguration(WebSecurityConfig.class) 를 적용시켜준다.

@WebMvcTest(CategoryController.class)
@ImportAutoConfiguration(WebSecurityConfig.class)
public class CategoryControllerTest extends ControllerSetting{

 

728x90

댓글