[에러노트] lambda$findInquiryById$1

hyewon jeong·2023년 6월 2일
0

에러노트

목록 보기
26/45

1 발생

문의글과 댓글 사이에 연관관계 매핑 후 test code를 작성하는데 에러가 발생했다.


2 코드

@Test
  @DisplayName("부모댓글이 없는 경우 - 댓글 등록 성공 ")
  void saveInquiryComment_comment_success() {
    //given
    int depth = 1;
    CreateContactCommentRequest createContactRequest = new CreateContactCommentRequest("comments",
        null);
    Inquiry inquiry = new Inquiry("username","nick","title","content",false);

    when(contactCommentRepository.save(any(ContactComment.class)))
        .thenReturn(createContactRequest.toEntity(inquiry, "username", "nickname", null, depth));
    when(inquiryRepository.existsById(inquiry.getId()))
        .thenReturn(true);
    when(inquiryRepository.findById(anyLong())).thenReturn(Optional.of(inquiry));

    //when
    contactCommentService.saveInquiryComment(inquiry.getId(), createContactRequest, "username", "nickname");
    //then
    verify(contactCommentRepository, times(1)).save(any(ContactComment.class));
    assertThat(createContactRequest.toEntity(inquiry, "username", "nickname", //저장된 댓글의 depth가 1이면 댓글임
        null, depth).getDepth()).isEqualTo(1);

  }


3 원인

챗 GPT 를 통해 알게 되었다.

inquiryRepository.findById(inquiryId) 메서드를 통해 조회한 결과가 존재하지 않을 때 orElseThrow 메서드가 실행되어 예외를 발생시키는 부분입니다. 즉, 주어진 inquiryId에 해당하는 조회 결과가 없을 경우 CustomException이 발생합니다.
오류를 해결하기 위해서는 테스트 코드에서 findInquiryById 메서드를 호출하기 전에 해당 inquiryId에 대한 데이터가 존재하는지 확인해야 합니다.

테스트 코드에서when(inquiryRepository.existsById(inquiry.getId())).thenReturn(true)을 통해 해당 inquiryId에 대한 데이터가 존재유무를 확인 한다고 생각했는데 이건 내가 정의한 메소드에 대해 true 값을 나타내는 것이지
inquiryId에 대한 데이터가 존재하는지는 알 수 없다.


4 해결

  @Test
  @DisplayName("부모댓글이 없는 경우 - 댓글 등록 성공 ")
  void saveInquiryComment_comment_success() {
    //given
    int depth = 1;
    CreateContactCommentRequest createContactRequest = new CreateContactCommentRequest("comments",
        null);
    Inquiry inquiry = new Inquiry("username","nick","title","content",false);

    when(contactCommentRepository.save(any(ContactComment.class)))
        .thenReturn(createContactRequest.toEntity(inquiry, "username", "nickname", null, depth));
    when(inquiryRepository.existsById(inquiry.getId()))
        .thenReturn(true);
    when(inquiryRepository.findById(inquiry.getId())).
        thenReturn(Optional.of(inquiry));
    //when
    contactCommentService.saveInquiryComment(inquiry.getId(), createContactRequest, "username", "nickname");
    //then
    verify(contactCommentRepository, times(1)).save(any(ContactComment.class));
    assertThat(createContactRequest.toEntity(inquiry, "username", "nickname", //저장된 댓글의 depth가 1이면 댓글임
        null, depth).getDepth()).isEqualTo(1);

  }
profile
개발자꿈나무

0개의 댓글