Web/Spring, SpringBoot

테스트에서 Entity vs DTO 이용

조용우 2025. 4. 2. 16:51

✅ 테스트에서 Request DTO를 사용하는 게 더 나은 경우

🔹 테스트가 Controller → Service 흐름을 따를 때

@WebMvcTest, MockMvc, 통합 테스트 등에서
실제 HTTP 요청처럼 흐름을 시뮬레이션하는 경우엔 CreatePostRequest DTO를 사용하는 게 자연스럽고, 검증이 더 현실적입니다.

mockMvc.perform(post("/api/posts")
        .contentType(MediaType.APPLICATION_JSON)
        .content(objectMapper.writeValueAsString(new CreatePostRequest("제목", "내용"))))
    .andExpect(status().isOk());

🟡 반면, 단위 테스트 (Service만 테스트) 중일 땐?

PostResponse response = postService.create(1L, "제목", "내용");
 

이런 식으로 직접 title, content 값을 넘기는 게 더 간결하고 명확합니다.

이유는?

  • Request DTO는 원래 Controller Layer의 역할이기 때문에
  • Service는 String title, String content를 받는 식으로 단위 테스트하는 게 맞음

📌 결론

테스트 성격 방식
단위 테스트 (Service) Entity or 필드 값 직접 넘기기
통합 테스트 (Controller 포함) Request DTO 사용하기 (CreatePostRequest)