Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 스프링 부트
- application.properties
- 리소스 서버
- JPA
- Spring Security
- rest api
- HttpMessageConverters
- cors
- Application Runner
- 브루트포스
- 백트래킹
- 스프링부트
- 알고리즘
- Application Event
- Application Argument
- 백기선
- WebApplication Type
- 외부설정
- AuthenticationPrincipal
- HATEOAS
- 리소스핸들러
- 정적 리소스
- webjar
- @ConfigurationProperties
- EnableAutoConfiguration
- 다익스트라
- 백준
- OAuth2
- @Profile
- JsonSerializer
Archives
- Today
- Total
아카이브
[스프링 기반 REST API 개발] 이벤트 수정 API 구현하기 본문
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
- 링크
- 수정한 이벤트 데이터
'Spring > 스프링 기반 REST API 개발' 카테고리의 다른 글
[스프링 기반 REST API 개발] Account 도메인 추가 (0) | 2021.01.09 |
---|---|
[스프링 기반 REST API 개발] 테스트 코드 리팩토링 (0) | 2021.01.09 |
[스프링 기반 REST API 개발] 이벤트 조회 API 구현하기 (0) | 2021.01.09 |
[스프링 기반 REST API 개발] 이벤트 목록 조회 API 구현 (0) | 2021.01.09 |
[스프링 기반 REST API 개발] API Index Handler, ErrorsResource 추가하기 (0) | 2021.01.06 |