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
반응형
'spring' 카테고리의 다른 글
[Spring] local cache key, value 조회 및 삭제 (0) | 2020.12.04 |
---|---|
[SpringBoot2] java config로 hikari datasource, transaction aop 설정 (0) | 2020.11.01 |
[SpringBoot] Jackson JsonAlias 설정 및 x-www-form-urlencoded 문제 해결 (0) | 2020.10.31 |
[spring] @ResponseBody Annotation vs ResponseEntity (0) | 2020.10.31 |
[spring] @Valid를 이용한 validation 체크와 custom annotation으로 validation (0) | 2020.10.31 |
댓글