-
MockMVC의 perform스프링 2023. 7. 21. 23:18
아래의 컨트롤러를 테스트하려고 했다.
@PostMapping(value = "/record-intake", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE}) @Operation(summary = "섭취기록", description = "일일 섭취량을 기록한다.") public ResponseEntity saveDailyIntake(@AuthenticationPrincipal Member member, @RequestBody @Valid IntakeFormRequest intakeFormRequest, BindingResult result) throws IOException { if (result.hasErrors()) { throw new FieldNotBindingException(NOT_VALID_INFO); }
테스트코드이다.
// given given(dailyIntakeService.saveDailyIntake(member, request, "raw String")) .willReturn(new MealPlan()); // when ResultActions result = mockMvc.perform(post("/api/record-intake") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(BaseResponse.success())) .with(csrf())); // then result.andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.message").value(DATA_SUCCESSFULLY_PROCESSED));
그러나 계속 400에러가 발생하면서 bindingResult에 에러가 잡히는 모습을 볼 수 있었다.
로그를 찍고, request의 값을 보았을 때 값이 할당되지 않고, null 값이 들어가는 모습을 볼 수 있었다.
RequestDTO에는 @NotNull이 있었기에 BindingResult에 에러가 잡히는것은 자명하다. 그러나 왜 request에 값이 null로 들어가는지 이해할 수 없었다.
장장 10시간의 구글링과 디버깅 끝에 답을 찾을 수 있었다.
mockMvc의 메소드
1) perform()
- 요청을 전송하는 역할을 합니다. 결과로 ResultActions 객체를 받으며, ResultActions 객체는 리턴 값을 검증하고 확인할 수 있는 andExcpect() 메소드를 제공해준다.
2) get("경로")
- HTTP 메소드를 결정할 수 있다. ( get(), post(), put(), delete() )
- 인자로는 경로를 보내준다.
3) params(info)
- 키=값의 파라미터를 전달할 수 있다.
- 여러 개일 때는 params()를, 하나일 때에는 param()을 사용.
4) andExpect()
- 응답을 검증하는 역할을 한다.
- 상태 코드 ( status() )
- 메소드 이름 : 상태코드
- isOk() : 200
- isNotFound() : 404
- isMethodNotAllowed() : 405
- isInternalServerError() : 500
- is(int status) : status 상태 코드
- 뷰 ( view() )
- 리턴하는 뷰 이름을 검증.
- ex. view().name("blog") : 리턴하는 뷰 이름이 blog인가?
- 리다이렉트 ( redirect() )
- 리다이렉트 응답을 검증.
- ex. redirectUrl("/blog") : '/blog'로 리다이렉트 되었는가?
- 모델 정보 ( model() )
- 컨트롤러에서 저장한 모델들의 정보 검증
- 응답 정보 검증 ( content() )
- 요청 Body의 content를 설정한다.
- contentType()
- 요청 헤더의 content type 설정
5) andDo(print())
- 요청/응답 전체 메세지를 확인할 수 있다.
즉, content에서 응답의 정보를 적어주었기 때문에 Request에 생성한 값들이 들어가지 않았기 때문이다. content에
생성한 request에 대한 정보를 넣어주어야 요청 Body에 대한 정보들을 넣을 수 있다.
하루 전부를 디버깅하는데 쏟다니... 힘들지만 뿌듯,,,^
728x90'스프링' 카테고리의 다른 글
mocking 아규먼트 불일치 (0) 2023.07.30 Mock에대한 고찰 (0) 2023.07.23 날짜 타입 JSON 변환에 관한 고찰 (0) 2023.05.15 노출하고싶지 않은 Json값 (1) 2023.04.13 Junit Access denied for user (0) 2023.04.05