@Test
@TestDescription("이벤트를 정상적으로 수정하기")
public void updateEvent() throws Exception {
Event event = this.generateEvent(200);
EventDto eventDto = this.modelMapper.map(event, EventDto.class);
String eventName = "수정한 이벤트";
eventDto.setName(eventName);
this.mockMvc.perform(put("/api/events/{id}", event.getId())
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("name").value(eventName))
.andExpect(jsonPath("_links.self").exists());
}
@Test
@TestDescription("입력값이 비어있는 경우의 수정 요청실패")
public void updateEvent400empty() throws Exception {
Event event = this.generateEvent(200);
EventDto eventDto = new EventDto();
this.mockMvc.perform(put("/api/events/{id}", event.getId())
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
@TestDescription("입력값이 잘못된 경우 수정 요청실패")
public void updateEvent400wrong() throws Exception {
Event event = this.generateEvent(200);
EventDto eventDto = new EventDto();
eventDto.setBasePrice(20000);
eventDto.setMaxPrice(1000);
this.mockMvc.perform(put("/api/events/{id}", event.getId())
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
@TestDescription("존재하지 않는 이벤트 수정 실패")
public void updateEvent404() throws Exception {
Event event = this.generateEvent(200);
EventDto eventDto = this.modelMapper.map(event, EventDto.class);
this.mockMvc.perform(put("/api/events/41223")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andDo(print())
.andExpect(status().isNotFound());
}
@PutMapping("/{id}")
public ResponseEntity updateEvent(@PathVariable Integer id,
@RequestBody @Valid EventDto eventDto,
Errors errors) {
Optional<Event> event = this.eventRepository.findById(id);
if (!event.isPresent()) {
return ResponseEntity.notFound().build();
}
if (errors.hasErrors()) {
return badRequest(errors);
}
this.eventValidator.validate(eventDto, errors);
if (errors.hasErrors()) {
return badRequest(errors);
}
Event existingEvent = event.get();
this.modelMapper.map(eventDto, existingEvent);
Event savedEvent = this.eventRepository.save(existingEvent);
EventResource eventResource = new EventResource(savedEvent);
eventResource.add(new Link("/docs/index.html#resources-events-get").withRel("profile"));
return ResponseEntity.ok(eventResource);
}