Spring/스프링 기반 REST API 개발
[스프링 기반 REST API 개발] 이벤트 수정 API 구현하기
주멘이
2021. 1. 9. 11:20
EventController에 updateEvent() 구현하기
@PutMapping("/{id}")
public ResponseEntity updateEvent(@PathVariable Integer id,
@RequestBody @Valid EventDto eventDto, Errors errors) {
Optional<Event> byId = this.eventRepository.findById(id);
if (byId.isEmpty()) { // 수정하려는 이벤트가 없는 경우, 404 NOT_FOUND
return ResponseEntity.notFound().build();
}
if (errors.hasErrors()) { // 입력 데이터 바인딩이 이상한 경우, 400 BAD_REQUEST
return badRequest(errors);
}
this.eventValidator.validate(eventDto, errors);
if (errors.hasErrors()) { // 도메인 로직 검증이 실패한 경우, 400 BAD_REQUEST
return badRequest(errors);
}
Event existingEvent = byId.get();
this.modelMapper.map(eventDto, existingEvent);
Event savedEvent = this.eventRepository.save(existingEvent);
/* HATEOAS links add */
EventResource eventResource = new EventResource(savedEvent);
eventResource.add(new Link("/docs/index.html#resources-events-update").withRel("profile"));
return ResponseEntity.ok(eventResource);
}
updateEvent Test 코드 작성
@Test
@TestDescription("이벤트를 정상적으로 수정하기")
void updateEvent() throws Exception {
// Given
Event event = this.generateEvent(200);
EventDto eventDto = this.modelMapper.map(event, EventDto.class);
String eventName = "Updated Event";
eventDto.setName(eventName);
// When & Then
this.mockMvc.perform(put("/api/events/{id}", event.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto))
)
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("name").value(eventName))
.andExpect(jsonPath("_links.self").exists())
;
}
@Test
@TestDescription("입력값이 비어있는 경우에 이벤트 수정 실패")
void updateEvent_400_Empty() throws Exception {
// Given
Event event = this.generateEvent(200);
EventDto eventDto = new EventDto();
String eventName = "Updated Event";
eventDto.setName(eventName);
// When & Then
this.mockMvc.perform(put("/api/events/{id}", event.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto))
)
.andDo(print())
.andExpect(status().isBadRequest())
;
}
@Test
@TestDescription("입력값이 잘못된 경우에 이벤트 수정 실패")
void updateEvent_400_Wrong() throws Exception {
// Given
Event event = this.generateEvent(200);
EventDto eventDto = this.modelMapper.map(event, EventDto.class);
eventDto.setBasePrice(20000);
eventDto.setMaxPrice(100);
// When & Then
this.mockMvc.perform(put("/api/events/{id}", event.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto))
)
.andDo(print())
.andExpect(status().isBadRequest())
;
}
@Test
@TestDescription("존재하지 않는 이벤트 수정 실패")
void updateEvent_404() throws Exception {
// Given
Event event = this.generateEvent(200);
EventDto eventDto = this.modelMapper.map(event, EventDto.class);
eventDto.setBasePrice(20000);
eventDto.setMaxPrice(100);
// When & Then
this.mockMvc.perform(put("/api/events/123123")
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto))
)
.andDo(print())
.andExpect(status().isNotFound())
;
}
테스트할 것
- 수정하려는 이벤트가 없는 경우, 404 NOT_FOUND
- 입력 데이터 바인딩이 이상한 경우, 400 BAD_REQUEST
- 도메인 로직 검증이 실패한 경우, 400 BAD_REQUEST
- (권한이 충분하지 않은 경우에 403 FORBIDDEN)
정상적으로 수정한 경우에 이벤트 리소스 응답
- 200 OK
- 링크
- 수정한 이벤트 데이터