2023.10.01 - [웹/Spring vue 웹 개발] - [리팩토링]게시판02(service/controller)
먼저 update가 jparepository에서는 직접적으로 제공하지 않기 때문에 만들어야합니다.
service 클래스의 update 입니다.
@Override
public Notice update(Long id,Notice saveNotice) {
//id 찾기
Optional<Notice> findNotice = noticeRepository.findById(id);
//존재여부 확인
if(findNotice.isPresent()==false){
return null;
}
//찾은후 데이터 업데이트 저장
Notice notice=findNotice.get();
notice.setTitle(saveNotice.getTitle());
notice.setContents(saveNotice.getContents());
return noticeRepository.save(notice);
}
그다음은 controller 클래스 update입니다.
@PutMapping("/{id}")
public ResponseEntity<Notice> update(@PathVariable Long id, @RequestBody Notice notice){
return ResponseEntity.ok(noticeService.update(id,notice));
}
테스트코드:
service update테스트
@Test
void update() throws Exception {
//생성
Long id = 1L;
Notice existingNotice = new Notice(id, "test","oldTitle", "oldContent", "oldEmail", "oldDate");
Notice updatedNotice = new Notice(id,"test", "newTitle", "newContent", "oldEmail", "oldDate");
//when
when(noticeRepository.findById(id)).thenReturn(Optional.of(existingNotice));
when(noticeRepository.save(any(Notice.class))).thenAnswer(invocation -> invocation.getArgument(0));
Notice result = noticeService.update(id, updatedNotice);
//then
assertThat(result.getId()).isEqualTo(id);
assertThat(result.getTitle()).isEqualTo("newTitle");
assertThat(result.getContents()).isEqualTo("newContent");
}
controller update 테스트
@Test
void update() throws Exception {
Long id = 1L;
Notice existingNotice = new Notice(id, "test","oldTitle", "oldContent", "oldEmail", "oldDate");
Notice updatedNotice = new Notice(id,"test", "newTitle", "newContent", "oldEmail", "oldDate");
when(noticeService.findById(id)).thenReturn(Optional.of(existingNotice));
when(noticeService.update(eq(id), any(Notice.class))).thenReturn(updatedNotice);
mockMvc.perform(put("/notice/" + id)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"newTitle\", \"contents\":\"newContent\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("newTitle"))
.andExpect(jsonPath("$.contents").value("newContent"));
}
앞단 프론트가 조금 시간이 걸려서 일단 프론트쪽 완성하고 백단 마무리 짓고 운영에 올리겠습니다. 주말마다 하다보니 진도가 늦네요.
'웹 > Spring vue 웹 개발' 카테고리의 다른 글
spring vue 댓글 01 (0) | 2023.10.09 |
---|---|
spring vue 게시판 리팩토링 완료 (프론트단 및 백단 연결 변경 완료) (0) | 2023.10.08 |
spring vue 게시판02 리팩토링 (service/controller) (0) | 2023.10.01 |
spring vue 게시판01 리팩토링 (data/repository) (0) | 2023.09.24 |
spring vue 장바구니 07 (0) | 2023.06.14 |