Junit Test Application-8-SecurityConfig JUnit 테스트

jaegeunsong97·2023년 8월 3일
0

Junit Bank Application 깃허브

Junit Bank Application 기록 노션

테스트 코드

package shop.mtcoding.bank.config;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;

@AutoConfigureMockMvc // Mock(가짜) 환경에 MockMvc가 등록됨
@SpringBootTest(webEnvironment = WebEnvironment.MOCK) // 가짜 환경 테스트
public class SecurityConfigTest {

     @Autowired
     private MockMvc mvc; // 가짜 환경에 등록된 MockMvc를 DI

     @Test
     public void authentication_test() throws Exception {
          // given

          // when
          ResultActions resultActions = mvc.perform(get("/api/s/hello"));
          String responseBody = resultActions.andReturn().getResponse().getContentAsString();
          int httpStatusCode = resultActions.andReturn().getResponse().getStatus();
          System.out.println("테스트 : " + responseBody);
          System.out.println("테스트 : " + httpStatusCode);

          // then
          
     }

     @Test
     public void authorization_test() throws Exception {
          // given

          // when

          // then

     }
}

이 부분에 대한 테스트, Junit, 포스트맨, 웹 전부 다른 형태로 나온다. 일관성 없음

따라서 SecurityConfig에 Exception 제어권을 가져오기

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

          // Exception 가로채기(일관성을 위해서)
          http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
               response.setContentType("application/json; charset=utf-8");
               response.setStatus(403);
               response.getWriter().println("error");
          });
          
          http.authorizeRequests()
                    .antMatchers("/api/s/**").authenticated()
                    .antMatchers("/api/admin/**").hasRole("" + UserEnum.ADMIN) // ROLE_
                    .anyRequest().permitAll();

          return http.build();

누구의 제어권을 가져오냐? authenticationEntryPoint가 파라미터로 받는 값의 타입이 AuthenticationEntryPoint이다. AuthenticationEntryPoint 내부를 가보면 commence 존재

내부의 commence에 request, resposne, authException 제어권 탈취

다음에는 이쁘게 나오도록 공통 DTO 만들예정

profile
블로그 이전 : https://medium.com/@jaegeunsong97

0개의 댓글