본문 바로가기
spring

[Spring] Mockmvc에 ExceptionHandler 등록

by moonsiri 2020. 10. 31.
728x90
반응형

Controller Test 를 위해 MockMvc 기반으로 Test를 할 때,

@ControllerAdvice 로 지정한 Global Exception Handler가 Test에서 동작하지 않을 때가 있습니다.

Mockmvc를 생성할때 아래와 같이 setControllerAdvice()로 사용할 class를 지정해주어야 합니다.

Normally @ControllerAdvice are auto-detected as long as they're declared as Spring beans. However since the standalone setup does not load any Spring config, they need to be registered explicitly here instead much like controllers.

@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@ComponentScan(...)
class SampleControllerTest {

    MockMvc mockMvc;

    @BeforEach
    void setUp() {
        SampleController controller = new SampleController();

        mockMvc = MockMvcBuilders
            .standaloneSetup(controller)
            .setControllerAdvice(GlobalExceptionHandler.class)  // ExceptionHandler 등록
            // .setControllerAdvice(new GlobalExceptionHandler())
        .build();
    }

    @Test
    void findOne_INVALID_PARAMETER() throws Exception {
        String url = "/sample/getInfo";

        MvcResult result = mockMvc.perform(
            post(url)
                .content("{}")
                .contentType(MediaType.APPLICATION_JSON_VALUE))
            .andDo(MockMvcResultHandlers.print())
            .andExpect(MockMvcResultMatchers.status().isBadRequest())
            .andReturn();

        String content = result.getResponse().getContentAsString();
        ObjectMapper om = new ObjectMapper();
        RtnVO rtnVO = om.readValue(content, RtnVO.class);

        Assertions.assertEquals(rtnVO.getErrorCd(), "INVALID_PARAMETER");
    }
@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(SampleException.class)
	public ResponseEntity<Object> SampleException(SampleException ex) {

		return new ResponseEntity<>(new RtnVO(INVALID_PARAMETER), HttpStatus.BAD_REQUEST);
	}
}
728x90
반응형

댓글