Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/#123 댓글 테스트 코드 구현 #125

Merged
merged 11 commits into from
Dec 4, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import kgu.developers.api.comment.presentation.exception.CommentNotFoundException;
import kgu.developers.api.comment.presentation.request.CommentRequest;
import kgu.developers.api.comment.presentation.request.CommentUpdateRequest;
import kgu.developers.api.comment.presentation.response.CommentListResponse;
import kgu.developers.api.comment.presentation.response.CommentPersistResponse;
import kgu.developers.api.post.application.PostService;
Expand All @@ -17,7 +19,6 @@
import kgu.developers.domain.comment.domain.CommentRepository;
import kgu.developers.domain.post.domain.Post;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
Expand Down Expand Up @@ -48,9 +49,9 @@ public CommentListResponse getComments(Long postId) {
}

@Transactional
public void updateComment(Long commentId, CommentRequest commentRequest) {
public void updateComment(Long commentId, CommentUpdateRequest request) {
Comment comment = getById(commentId);
comment.updateContent(commentRequest.content());
comment.updateContent(request.content());
minjo-on marked this conversation as resolved.
Show resolved Hide resolved
}

@Transactional
Expand All @@ -59,7 +60,7 @@ public void deleteComment(Long commentId) {
comment.delete();
}

private Comment getById(Long commentId) {
public Comment getById(Long commentId) {
return commentRepository.findById(commentId)
.filter(comment -> comment.getDeletedAt() == null)
.orElseThrow(CommentNotFoundException::new);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,31 @@

import static org.springframework.http.HttpStatus.CREATED;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import kgu.developers.api.comment.application.CommentService;
import kgu.developers.api.comment.presentation.request.CommentRequest;
import kgu.developers.api.comment.presentation.request.CommentUpdateRequest;
import kgu.developers.api.comment.presentation.response.CommentListResponse;
import kgu.developers.api.comment.presentation.response.CommentPersistResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
Expand All @@ -39,7 +42,7 @@ public class CommentController {
@ApiResponse(responseCode = "201", content = @Content(schema = @Schema(implementation = CommentPersistResponse.class)))
@PostMapping
public ResponseEntity<CommentPersistResponse> createComment(
@RequestBody CommentRequest commentRequest
@RequestBody @Valid CommentRequest commentRequest
) {
CommentPersistResponse response = commentService.createComment(commentRequest);
return ResponseEntity.status(CREATED).body(response);
Expand All @@ -52,10 +55,10 @@ public ResponseEntity<CommentPersistResponse> createComment(
@ApiResponse(responseCode = "204")
@PatchMapping("/{commentId}")
public ResponseEntity<Void> updateComment(
@Parameter(description = "수정할 게시글의 id", example = "1", required = true) @PathVariable @Positive Long commentId,
@RequestBody CommentRequest commentRequest
@Parameter(description = "수정할 댓글의 id", example = "1", required = true) @PathVariable @Positive Long commentId,
@RequestBody @Valid CommentUpdateRequest request
) {
commentService.updateComment(commentId, commentRequest);
commentService.updateComment(commentId, request);
return ResponseEntity.noContent().build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.Builder;

@Builder
public record CommentRequest(
@Schema(description = "게시물 아이디", example = "1", requiredMode = REQUIRED)
@NotNull
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package kgu.developers.api.comment.presentation.request;

import static io.swagger.v3.oas.annotations.media.Schema.RequiredMode.REQUIRED;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Builder;

@Builder
public record CommentUpdateRequest(
@Schema(description = "댓글 내용", example = "예시 코멘트입니다, 좋은 소식이네요!", requiredMode = REQUIRED)
@NotBlank
String content
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package comment.application;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import kgu.developers.api.comment.application.CommentService;
import kgu.developers.api.comment.presentation.exception.CommentNotFoundException;
import kgu.developers.api.comment.presentation.request.CommentRequest;
import kgu.developers.api.comment.presentation.request.CommentUpdateRequest;
import kgu.developers.api.comment.presentation.response.CommentListResponse;
import kgu.developers.api.comment.presentation.response.CommentPersistResponse;
import kgu.developers.api.comment.presentation.response.CommentResponse;
import kgu.developers.domain.comment.domain.Comment;
import kgu.developers.domain.post.domain.Category;
import kgu.developers.domain.post.domain.Post;
import kgu.developers.domain.user.domain.Major;
import kgu.developers.domain.user.domain.User;
import mock.FakeCommentRepository;
import mock.TestContainer;

public class CommentServiceTest {
private CommentService commentService;

@BeforeEach
public void init() {
FakeCommentRepository fakeCommentRepository = new FakeCommentRepository();
TestContainer testContainer = new TestContainer();

this.commentService = new CommentService(fakeCommentRepository, testContainer.postService,
testContainer.userService);

testContainer.userRepository.save(User.builder()
.id("202411345")
.password("password1234")
.name("홍길동")
.email("[email protected]")
.phone("010-1234-5678")
.major(Major.CSE)
.build());

User author = testContainer.userService.getUserById("202411345");

Post post = testContainer.postRepository.save(Post.create(
"테스트용 제목1", "테스트용 내용1", Category.DEPT_INFO, author
));

Comment delete = fakeCommentRepository.save(Comment.builder()
.author(testContainer.userService.getUserById("202411345"))
.content("deleted")
.post(post)
.build()
);
delete.delete();

fakeCommentRepository.save(Comment.builder()
.author(testContainer.userService.getUserById("202411345"))
.content("get")
.post(post)
.build()
);

fakeCommentRepository.save(Comment.builder()
.author(testContainer.userService.getUserById("202411345"))
.content("test!")
.post(post)
.build()
);

UserDetails user = testContainer.userService.getUserById("202411345");
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(
new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities())
);
}

@Test
@DisplayName("createComment는 댓글을 생성할 수 있다.")
public void createComment_Success() {
// given
CommentRequest commentRequest = CommentRequest.builder()
.content("test")
.postId(1L)
.build();

// when
CommentPersistResponse response = commentService.createComment(commentRequest);

// then
assertEquals(response.commentId(), 4L);
assertEquals(commentService.getById(4L).getContent(), "test");
}
minjo-on marked this conversation as resolved.
Show resolved Hide resolved

@Test
@DisplayName("getComments는 등록된 순서 오름차순으로 정렬하고, 삭제된 댓글을 제외하여 조회한다.")
public void getComments_Success() {
// given
Long postId = 1L;

// when
CommentListResponse response = commentService.getComments(postId);
List<CommentResponse> comments = response.contents();

// then
assertEquals(comments.size(), 2);
assertEquals(comments.get(0).content(), "get");
assertEquals(comments.get(1).content(), "test!");
}

@Test
@DisplayName("updateComment는 댓글의 내용을 수정할 수 있다.")
public void updateComment_Success() {
// given
Long commentId = 2L;
CommentUpdateRequest request = CommentUpdateRequest.builder()
.content("update")
.build();

// when
commentService.updateComment(commentId, request);

// then
assertEquals(commentService.getById(commentId).getContent(), "update");
}

@Test
@DisplayName("deleteComment는 댓글을 삭제할 수 있다.")
public void deleteComment_Success() {
// given
Long commentId = 2L;

// when
commentService.deleteComment(commentId);

// then
assertThatThrownBy(() -> commentService.getById(commentId))
.isInstanceOf(CommentNotFoundException.class)
.hasMessage("해당 댓글을 찾을 수 없습니다.");
}

@Test
@DisplayName("getById는 해당 댓글을 가져올 수 있다.")
public void getById_Success() {
// given
Long commentId = 2L;

// when
Comment response = commentService.getById(commentId);

// then
assertEquals(response.getId(), commentId);
assertEquals(response.getContent(), "get");
}

@Test
@DisplayName("getById는 존재하지 않는 댓글을 조회할 경우 CommentNotFoundException을 발생시킨다.")
public void getById_NotFound_ThrowsException() {
// given
Long commentId = 0L;

// when
// then
assertThatThrownBy(() -> commentService.getById(commentId))
.isInstanceOf(CommentNotFoundException.class)
.hasMessage("해당 댓글을 찾을 수 없습니다.");
}
minjo-on marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package comment.presentation;

public class CommentControllerTest {
}
7 changes: 7 additions & 0 deletions aics-api/src/testFixtures/java/mock/TestContainer.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,20 @@

import kgu.developers.api.auth.application.AuthService;
import kgu.developers.api.auth.presentation.AuthController;
import kgu.developers.api.post.application.PostService;
import kgu.developers.api.user.application.UserService;
import kgu.developers.common.auth.jwt.JwtProperties;
import kgu.developers.common.auth.jwt.TokenProvider;
import kgu.developers.domain.post.domain.PostRepository;
import kgu.developers.domain.user.domain.UserRepository;

public class TestContainer {
public final UserRepository userRepository;
public final UserService userService;
public final AuthService authService;
public final AuthController authController;
public final PostService postService;
public final PostRepository postRepository;

public TestContainer() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
Expand All @@ -33,5 +37,8 @@ public TestContainer() {
this.authController = AuthController.builder()
.authService(this.authService)
.build();

this.postRepository = new FakePostRepository();
this.postService = new PostService(postRepository, userService);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package comment.application;

public class CommentServiceTest {
}
Loading
Loading