inflearn logo
강의

Course

Instructor

Learning Large-Scale System Design by Building Directly with Spring Boot - Bulletin Board

CommentApiTest 중 오류가 발생합니다

Resolved

105

jackt0506

4 asked

0

섹션3 23강 댓글 최대 2 depth - CUD API 테스트 & 테스트 데이터 삽입 파트 수강 중

create 테스트를 실행하는데 오류가 계속 발생합니다

package kuke.board.comment.api;

import kuke.board.comment.service.response.CommentResponse;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestClient;

public class CommentApiTest {
    RestClient restClient = RestClient.create("http://localhost:9001");

    @Test
    void create() {
        CommentResponse response1 = createComment(new CommentCreateRequest(1L, "my comment1", null, 1L));
        CommentResponse response2 = createComment(new CommentCreateRequest(1L, "my comment2", response1.getCommentId(), 1L));
        CommentResponse response3 = createComment(new CommentCreateRequest(1L, "my comment3", response1.getCommentId(), 1L));

        System.out.println("commentId=%s".formatted(response1.getCommentId()));
        System.out.println("\tcommentId=%s".formatted(response2.getCommentId()));
        System.out.println("\tcommentId=%s".formatted(response3.getCommentId()));

//        commentId=123694721668214784
//          commentId=123694721986981888
//          commentId=123694722045702144
    }

    CommentResponse createComment(CommentCreateRequest request) {
        return restClient.post()
                .uri("/v1/comments")
                .body(request)
                .retrieve()
                .body(CommentResponse.class);
    }

    @Getter
    @AllArgsConstructor
    public static class CommentCreateRequest {
        private Long articleId;
        private String content;
        private Long parentCommentId;
        private Long writerId;
    }
}
  

코드는 강사님 코드를 복붙을 해 봤는데도 아래의 오류가 지속적으로 발생합니다

500 Internal Server Error: "{"timestamp":"2025-08-24T11:27:31.828+00:00","status":500,"error":"Internal Server Error","path":"/v1/comments"}"

org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Internal Server Error: "{"timestamp":"2025-08-24T11:27:31.828+00:00","status":500,"error":"Internal Server Error","path":"/v1/comments"}"

at org.springframework.web.client.HttpServerErrorException.create(HttpServerErrorException.java:102)

at org.springframework.web.client.StatusHandler.lambdadefaultHandlerdefaultHandler3(StatusHandler.java:89)

at org.springframework.web.client.StatusHandler.handle(StatusHandler.java:146)

at org.springframework.web.client.DefaultRestClient$DefaultResponseSpec.applyStatusHandlers(DefaultRestClient.java:698)

at org.springframework.web.client.DefaultRestClient.readWithMessageConverters(DefaultRestClient.java:200)

at org.springframework.web.client.DefaultRestClient$DefaultResponseSpec.readBody(DefaultRestClient.java:685)

at org.springframework.web.client.DefaultRestClient$DefaultResponseSpec.body(DefaultRestClient.java:631)

at kuke.board.comment.api.CommentApiTest.createComment(CommentApiTest.java:32)

at kuke.board.comment.api.CommentApiTest.create(CommentApiTest.java:14)

at java.base/java.lang.reflect.Method.invoke(Method.java:580)

at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)

at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)

image.png

 

image.png

DB를 봤을 때 parent_comment_id 가 NOT NULL이라 안 되나 싶다가도
강사님은 pdf의
create table comment (

comment_id bigint not null primary key,

content varchar(3000) not null,

article_id bigint not null,

parent_comment_id bigint not null,

writer_id bigint not null,

deleted bool not null,

created_at datetime not null

);

sql문과 똑같이 만들었던걸 생각하면 아닌 거 같기도 하고 뭐가 문제인지 감이 안 옵니다

 

@Service
@RequiredArgsConstructor
public class CommentService {
    private final Snowflake snowflake = new Snowflake();
    private final CommentRepository commentRepository;

    @Transactional
    public CommentResponse create(CommentCreateRequest request) {
        Comment parent = findParent(request);
        Comment comment = commentRepository.save(
                Comment.create(
                        snowflake.nextId(),
                        request.getContent(),
                        parent == null ? null : parent.getCommentId(),
                        request.getArticleId(),
                        request.getWriterId()
                )
        );
        return CommentResponse.from(comment);
    }

    private Comment findParent(CommentCreateRequest request) {
        Long parentCommentId = request.getParentCommentId();
        if ( parentCommentId == null) {
            return null;
        }
        return commentRepository.findById(parentCommentId)
                .filter(not(Comment::getDeleted))
                .filter(Comment::isRoot)
                .orElseThrow();
    }

    public CommentResponse read(Long commentId) {
        return CommentResponse.from(
                commentRepository.findById(commentId).orElseThrow()
        );
    }

    @Transactional
    public void delete(Long commentId) {
        commentRepository.findById(commentId)
                .filter(not(Comment::getDeleted))
                .ifPresent(comment -> {
                    if (hasChildren(comment)) {
                        comment.delete();
                    } else {
                        delete(comment);
                    }
                });
    }

    private boolean hasChildren(Comment comment) {
        return commentRepository.countBy(comment.getArticleId(), comment.getCommentId(), 2L) == 2;
    }

    private void delete(Comment comment) {
        commentRepository.delete(comment);
        if (!comment.isRoot()) {
            commentRepository.findById(comment.getParentCommentId())
                    .filter(Comment::getDeleted)
                    .filter(not(this::hasChildren))
                    .ifPresent(this::delete);
        }
    }
}

서비스의 경우에도 딱히 차이점을 발견하지 못했고 혹시나 싶어 복붙을 해도 마찬가지의 오류가 발생합니다

java mysql spring-boot

Answer 2

0

kuke

jackt0506님, 안녕하세요!

 

올려주신건 테스트 코드(클라이언트)의 에러 로그이고, 단순히 서버에서 500 응답을 내려줬을 뿐이라 상세한 정보가 없습니다.

발생한 에러에 대해 상세한 원인을 찾고 추적하시려면 서버 애플리케이션의 에러 로그를 살펴보셔야 합니다.

서버 애플리케이션 에러 로그에 구체적인 정보가 있을거라, 이를 기반으로 다시 확인해보시겠어요?

그래도 추적이 어려우시면, 에러 로그도 공유해주시면 저도 같이 살펴보겠습니다!

1

jackt0506

감사합니다 그냥 테스트 쪽에서 나오는 것만 보고 이게 뭐지 하고 있었는데 서버 애플리케이션을 확인 해보니 금방 해결했습니다!

0

jackt0506

server.port: 9001
spring:
  application:
    name: kuke-board-comment-service
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/comment
    username: root
    password: root
  jpa:
    database-platform: org.hibernate.dialect.MySQLDialect
    open-in-view: false
    show-sql: true
    hibernate:
      ddl-auto: none

application.yml은 이렇게 해뒀습니다

consumer에서 에러가 발생할 경우 데이터 유실 문의

0

34

2

게시글 테스트 데이터 삽입

0

41

2

정렬, 필터, 검색 등의 조건이 붙을 경우 최적화할 수 있는 방법이 무엇이 있을까요?

0

91

2

좋아요 기능 정합성 보장 방법

0

87

2

좋아요 동시성처리 최적의 선택?

1

108

2

프론트엔드 msa 환경 api 주소 통합? 과 서버끼리 통신 방식에대해

0

82

2

안녕하세요 무한스크롤 강의듣다가 질문이 있습니다.

0

51

1

조회수 조회 로직 질문

1

59

2

비로그인 유저도 어뷰징 방지 정책

1

60

2

CommentServiceTest의 테스트 로직 질문

0

47

2

무한 스크롤 방식에서 페이지 번호 방식 쿼리의 문제점 의문

1

68

2

path 쿼리 관련 질문드립니다!

0

50

2

antigravity 에디터를 쓰신다면 종료해주세요

1

115

0

프로젝트 구조

0

79

2

article_like_count api test

0

65

2

이벤트 페이로드 객체의 생성 방식이 팩토리 메서드 패턴이 아닌 빌더 패턴인 이유가 궁금합니다!.

0

93

2

[33. 좋아요 수 구현] 에서 테스트 하는 화면 동시성 문제

0

81

2

findByPath에서 articleId로도 검색을 해야 할 것 같아요.

0

84

3

jpa ddl-auto none을 하는 이유와 join 방법

0

90

2

팩터리 메소드와 response 객체 사용 이유가 궁금합니다!

0

82

2

커서 기반 페이지네이션 과 무한 스크롤링

0

91

2

게시글 생성 로직에서 오류 발생시 redis 게시글 수 되돌리기

0

92

2

멀티 모듈이 아닌 MSA 환경에서 common

0

143

2

2Depth 강의 도중 궁금한 점 있어요!!

0

69

2