강의

멘토링

로드맵

Inflearn brand logo image

인프런 커뮤니티 질문&답변

jackt0506님의 프로필 이미지
jackt0506

작성한 질문수

스프링부트로 직접 만들면서 배우는 대규모 시스템 설계 - 게시판

CommentApiTest 중 오류가 발생합니다

해결된 질문

작성

·

62

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);
        }
    }
}

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

답변 2

0

쿠케님의 프로필 이미지
쿠케
지식공유자

jackt0506님, 안녕하세요!

 

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

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

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

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

jackt0506님의 프로필 이미지
jackt0506
질문자

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

0

jackt0506님의 프로필 이미지
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은 이렇게 해뒀습니다

jackt0506님의 프로필 이미지
jackt0506

작성한 질문수

질문하기