Test Code ‐ Presentation Layer(프레젠테이션 레이어) 테스트 - dnwls16071/Backend_Study_TIL GitHub Wiki

📚 Presentation Layer

  • 외부 세계의 요청을 가장 먼저 받는 계층이다.
  • 파라미터에 대한 최소한의 검증을 수행한다.

📚 MockMvc

  • Mock(가짜) 객체를 사용해 스프링 MVC 동작을 재현할 수 있는 테스트 프레임워크이다.

📚 Presentation Layer 테스트

package com.spoteditor.backend.place.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spoteditor.backend.place.controller.dto.PlaceRegisterRequest;
import com.spoteditor.backend.place.entity.Address;
import com.spoteditor.backend.place.repository.PlaceRepository;
import com.spoteditor.backend.place.service.PlaceService;
import com.spoteditor.backend.place.service.dto.PlaceRegisterCommand;
import com.spoteditor.backend.place.service.dto.PlaceRegisterResult;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import java.util.List;

import static com.spoteditor.backend.place.entity.Category.TOUR;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

@WebMvcTest(controllers = PlaceApiController.class)
class PlaceApiControllerTest {

	@Autowired private MockMvc mockMvc;
	@Autowired private ObjectMapper objectMapper;	// 직렬화 / 역직렬화위한 매핑

	@MockitoBean private PlaceService placeService;
	@MockitoBean private PlaceRepository placeRepository;

	@Test
	@DisplayName("공간을 추가한다.")
	void 공간을_추가한다() throws Exception {

		// given
		Long userId = 1L;

		PlaceRegisterRequest request = PlaceRegisterRequest.builder()
				.name("공간1")
				.description("공간1")
				.originalFile("원본 파일")
				.address(Address.builder()
						.address("테스트1")
						.roadAddress("테스트1")
						.latitude(37.123)
						.longitude(128.123)
						.sido("테스트1")
						.bname("테스트1")
						.sigungu("테스트1")
						.build())
				.category(TOUR)
				.build();

		PlaceRegisterResult mockResult = new PlaceRegisterResult(
				userId,
				1L,
				request.name(),
				request.description(),
				0,
				request.address(),
				request.category(),
				List.of()
		);


		when(placeService.addPlace(eq(userId), any(PlaceRegisterCommand.class)))
				.thenReturn(mockResult);

		// when & then
		mockMvc.perform(MockMvcRequestBuilders.post("/api/places")
				.param("userId", String.valueOf(userId))
				.content(objectMapper.writeValueAsString(request))
				.contentType(MediaType.APPLICATION_JSON))
				.andExpect(MockMvcResultMatchers.status().isCreated());
	}
}