2023.10.01 - [웹/Spring vue 웹 개발] - [리팩토링]게시판02(service/controller)

[리팩토링]게시판02(service/controller)

이전글: 2023.09.24 - [웹/Spring vue 웹 개발] - [리팩토링] 게시판01(data/repository) [리팩토링] 게시판01 앞서 말씀 드리자면 jpa를 조금 독학으로 하다보니 코드가 조금 중구난방이어서 김영한 개발자님

kwaksh2319.tistory.com

먼저 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"));
    }

앞단 프론트가 조금 시간이 걸려서 일단 프론트쪽 완성하고 백단 마무리 짓고 운영에 올리겠습니다. 주말마다 하다보니 진도가 늦네요.

+ Recent posts