package com.rest.api;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.time.LocalDateTime;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rest.api.events.Event;
import com.rest.api.events.EventRepository;
@RunWith(SpringRunner.class)
@WebMvcTest
public class EventControllerTests {
@Autowired
MockMvc mockMvc; // 요청 작성, 응답 검증
@Autowired
ObjectMapper objectMapper;
@MockBean
EventRepository eventRepository;
@Test
public void createEvent() throws Exception {
Event event = Event.builder()
.name("PMH")
.description("REST API Development with Spring")
.beginEnrollmentDateTime(LocalDateTime.of(2022, 03, 12, 14, 21))
.closeEnrollmentDateTime(LocalDateTime.of(2022, 03, 13, 14, 21))
.beginEventDateTime(LocalDateTime.of(2022, 03, 14, 14, 21))
.endEventDateTime(LocalDateTime.of(2022, 03, 15, 14, 21))
.basePrice(100)
.maxPrice(200)
.limitOfEnrollment(100)
.location("선릉역 1번 출구")
.build();
event.setId(10);
Mockito.when(eventRepository.save(event)).thenReturn(event); // event를 저장하면 event entity를 반환하라고 명령
mockMvc.perform(post("/api/events/")
.contentType(MediaType.APPLICATION_JSON_VALUE) // 보낼 요청의 타입
.accept(MediaTypes.HAL_JSON) // 받고 싶은 데이터 타입
.content(objectMapper.writeValueAsString(event))
)
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("id").exists())
.andExpect(header().exists(HttpHeaders.LOCATION))
.andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaTypes.HAL_JSON_VALUE));
}
}
.jsonPath() : json 객체를 쉽게 탐색하도록 도와주는 함수
'JUnit' 카테고리의 다른 글
(JUnit) .andExpect로 특정 상황에 따른 테스트를 진행 (0) | 2022.03.12 |
---|