본문 바로가기
Programming/TDD Project

Pull Request 009 - 자유게시글 수정 기능 TDD로 구현해보기

by JKROH 2023. 11. 9.
반응형

 지난 글까지 자유 게시글 작성 기능을 모두 마쳤다. 이제는 자유게시글의 수정 기능을 구현해보려 한다. 아 그리고 지난 글의 마지막에서 언급했던 설계 수정은 다시 원상복구 했다. 이유는 다음과 같다.

  • 서비스 레이어의 한 클래스는 엔트리 포인트 역할을 담당하긴 해야한다. 그렇지 않으면 컨트롤러와의 의존 관계가 너무 복잡해진다.
  • 결국 컨트롤러와 통신하는 계층과 레파지토리와 통신하는 계층이 나뉘는 형태를 유지한다.
  • 의존관계가 많이 물려 테스트하기 어렵긴 하다. 이 부분은 천천히 고쳐나가보자.

 아무튼 자유 게시글의 수정 로직은 다음과 같다.

  1. 자유게시글 수정은 FreeBoardCommandService#updateFreeBoard(FreeBoard freeboard, FreeBoardDto.Put putDto);에서 담당한다.
    1. 이 때, 제목과 내용은 null이 되면 안된다. 해당 검증은 DTO에서 직접 처리한다.
  2. 내용 수정은 엔티티에서 직접 처리한다. FreeBoard.modify(FreeBoardDto.Put putDto)을 통해 인자로 넘어온 Put DTO의 값들을 기반으로 엔티티 내용을 수정한다.
  3. 내용 수정을 마치면 해당 엔티티를 반환한다.

 여기서 우리가 테스트 해 볼 수 있는 내용은 1, 2번이 될 것이다. 해당 로직에 대한 테스트를 먼저 작성하자.

    @Test
    void updateTest() {
        FreeBoard testEntity = FreeBoard.builder()
                .title("test")
                .content("content")
                .build();
        testEntity.setId(1L);

        FreeBoardDto.Put putDto = new FreeBoardDto.Put();
        putDto.setTitle("modifiedTitle");
        putDto.setContent("modifiedContent");

        freeBoardCommandService.update(testEntity, putDto);

        assertThat(testEntity.getTitle()).isEqualTo(putDto.getTitle());
        assertThat(testEntity.getContent()).isEqualTo(putDto.getContent());
    }

/////////////////////////

    @Test
    void testModify() {
        FreeBoard testEntity = FreeBoard.builder()
                .title("test")
                .content("content")
                .build();
        testEntity.setId(1L);

        FreeBoardDto.Put putDto = new FreeBoardDto.Put();
        putDto.setTitle("modifiedTitle");
        putDto.setContent("modifiedContent");

        testEntity.modify(putDto);

        assertThat(testEntity.getTitle()).isEqualTo(putDto.getTitle());
        assertThat(testEntity.getContent()).isEqualTo(putDto.getContent());
    }

 

 해당 메서드를 테스트하는 것은 굉장히 쉽다. 별도로 레포지토리에 뭔가를 저장하라고 요청하지 않아도 되며, 그저 엔티티 값을 수정하면 JPA에서 알아서 값을 수정해주기 때문에, 우리는 값이 잘 바뀌었는지만 테스트해보면 된다. 물론 이 역시 추후 레파지토리를 테스트하는 과정에서 실제로 수정이 잘 되었는지를 확인해봐야 할 것이다.

 

 이렇게 작성한 테스트에 맞춰 Put DTO클래스와 FreeBoardCommandService#update(), FreeBoard#modify()를 정의해보자.

    @Getter
    @Setter
    public static class Put {
        private String title;
        private String content;
    }

/////////////////////////

    @Transactional
    public void update(FreeBoard entity, FreeBoardDto.Put putDto) {
        entity.modify(putDto);
    }
    
/////////////////////////    

    public void modify(FreeBoardDto.Put putDto) {
        this.title = putDto.getTitle();
        this.content = putDto.getContent();
    }

 

 추후 필요한 데이터가 더 발생하면 그만큼 코드가 길어질 것이다.

 

 이렇게 수정 기능에 대한 테스트 작성과 기능 구현은 모두 끝났다. put을 쓴 이유는 FreeBoard#modify(); 메서드의 로직을 보면 알 수 있다. 굳이 일일이 사용자가 입력하지 않은 데이터가 있는지를 검증하는 것보다, 기존에 입력되어있던 데이터는 그대로 넘어와서 그대로 남겨놓고 새롭게 바뀐 값은 바꿔준다. 그래서 Put을 사용한 것이다. 물론 null에 대한 처리도 잊지 않았다.

 

전체 코드는 링크에서 확인할 수 있다.

반응형

댓글