[Spring] Junit- Multipartfile과 DTO를 전달받는 API 단위 테스트

윤성철·2024년 9월 24일

Back-End

목록 보기
13/22
post-thumbnail

서론

테스트코드를 작성하면서, form-data타입으로 DTO 객체와 Multipartfile 객체를 받는 컨트롤러 계층에서 마주한 이슈와 해결과정을 기록하고자 한다.

본론

사용자의 프로필을 수정하는 컨트롤러에서, 수정할 닉네임은 DTO 객체로, 프로필 사진은 Multipartfile로 받아서 서비스계층의 메서드를 호출한다.

UserController

  • 해당 컨트롤러의 API의 테스트를 수행하기 위해, DTO 객체를 objectMapper를 통해 DTO -> string -> multipartfile 객체로 전환하여, 테스트코드를 작성하는 방법을 탐색할 수 있었다.
  1. 먼저 Stub 객체를 생성한다.

UserObjectFixture

  1. 위에서 말했듯, DTO를 Multipartfile로 전환한다.
MockMultipartFile file = new MockMultipartFile("file", fileName, contentType, "test data".getBytes(StandardCharsets.UTF_8));

MockMultipartFile requestDto = new MockMultipartFile("requestDto", "request.json", "application/json", mapper.writeValueAsBytes(updateRequest));
  1. mockMvc로 테스트 수행 간, MockMultipartfile로 전환한 DTO, multipartfile 이미지를 파라미터로 넘겨준다.
 mockMvc.perform(multipart(HttpMethod.PUT,"/api/v1/user/profile")
                .file(file)
                .file(requestDto)
                        .with(csrf()))
                .andExpect(status().isOk())
                .andDo(print());

테스트가 정상적으로 수행되었다.

전체 코드

profile
내 기억보단 내가 작성한 기록을 보자..

0개의 댓글