Skip to content

Commit d93d130

Browse files
committed
Test: 테스트 작성
1 parent e97cdef commit d93d130

File tree

2 files changed

+226
-1
lines changed

2 files changed

+226
-1
lines changed

src/test/java/com/back/domain/user/controller/UserControllerTest.java

Lines changed: 143 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ class UserControllerTest {
4949
@Autowired
5050
private PostRepository postRepository;
5151

52+
@Autowired
53+
private CommentRepository commentRepository;
54+
5255
@Autowired
5356
private TestJwtTokenProvider testJwtTokenProvider;
5457

@@ -661,7 +664,7 @@ void deleteMyAccount_expiredAccessToken() throws Exception {
661664
.andExpect(jsonPath("$.message").value("만료된 액세스 토큰입니다."));
662665
}
663666

664-
// ====================== 내 게시글 목록 조회 테스트 ======================
667+
// ====================== 내 게시글 목록 조회 테스트 ======================
665668

666669
@Test
667670
@DisplayName("내 게시글 목록 조회 성공 → 200 OK")
@@ -795,4 +798,143 @@ void getMyPosts_expiredAccessToken() throws Exception {
795798
.andExpect(jsonPath("$.code").value("AUTH_004"))
796799
.andExpect(jsonPath("$.message").value("만료된 액세스 토큰입니다."));
797800
}
801+
802+
// ====================== 내 댓글 목록 조회 테스트 ======================
803+
804+
@Test
805+
@DisplayName("내 댓글 목록 조회 성공 → 200 OK")
806+
void getMyComments_success() throws Exception {
807+
// given: 정상 유저 + 게시글 + 댓글 2개 생성
808+
User user = User.createUser("commenter", "[email protected]", passwordEncoder.encode("P@ssw0rd!"));
809+
user.setUserProfile(new UserProfile(user, "닉네임", null, null, null, 0));
810+
user.setUserStatus(UserStatus.ACTIVE);
811+
userRepository.save(user);
812+
813+
Post post = new Post(user, "스프링 트랜잭션 정리", "내용입니다.", null);
814+
postRepository.save(post);
815+
816+
Comment parent = new Comment(post, user, "코딩 박사의 스프링 교재도 추천합니다.", null);
817+
Comment comment1 = new Comment(post, user, "정말 도움이 많이 됐어요!", null);
818+
Comment comment2 = new Comment(post, user, "감사합니다! 더 공부해볼게요.", parent);
819+
commentRepository.saveAll(List.of(parent, comment1, comment2));
820+
821+
String accessToken = generateAccessToken(user);
822+
823+
// when
824+
ResultActions resultActions = mvc.perform(
825+
get("/api/users/me/comments")
826+
.header("Authorization", "Bearer " + accessToken)
827+
.param("page", "0")
828+
.param("size", "10")
829+
).andDo(print());
830+
831+
// then
832+
resultActions
833+
.andExpect(status().isOk())
834+
.andExpect(jsonPath("$.success").value(true))
835+
.andExpect(jsonPath("$.code").value("SUCCESS_200"))
836+
.andExpect(jsonPath("$.message").value("내 댓글 목록이 조회되었습니다."))
837+
.andExpect(jsonPath("$.data.items").isArray())
838+
.andExpect(jsonPath("$.data.items.length()").value(3))
839+
.andExpect(jsonPath("$.data.items[0].content").value("감사합니다! 더 공부해볼게요."))
840+
.andExpect(jsonPath("$.data.items[1].content").value("정말 도움이 많이 됐어요!"));
841+
}
842+
843+
@Test
844+
@DisplayName("존재하지 않는 사용자 → 404 Not Found")
845+
void getMyComments_userNotFound() throws Exception {
846+
// given
847+
String fakeToken = testJwtTokenProvider.createAccessToken(999L, "ghost", "USER");
848+
849+
// when & then
850+
mvc.perform(get("/api/users/me/comments")
851+
.header("Authorization", "Bearer " + fakeToken))
852+
.andDo(print())
853+
.andExpect(status().isNotFound())
854+
.andExpect(jsonPath("$.code").value("USER_001"))
855+
.andExpect(jsonPath("$.message").value("존재하지 않는 사용자입니다."));
856+
}
857+
858+
@Test
859+
@DisplayName("탈퇴한 계정 → 410 Gone")
860+
void getMyComments_deletedUser() throws Exception {
861+
// given
862+
User user = User.createUser("deleted", "[email protected]", passwordEncoder.encode("P@ssw0rd!"));
863+
user.setUserProfile(new UserProfile(user, "닉네임", null, null, null, 0));
864+
user.setUserStatus(UserStatus.DELETED);
865+
userRepository.save(user);
866+
867+
String accessToken = generateAccessToken(user);
868+
869+
// when & then
870+
mvc.perform(get("/api/users/me/comments")
871+
.header("Authorization", "Bearer " + accessToken))
872+
.andDo(print())
873+
.andExpect(status().isGone())
874+
.andExpect(jsonPath("$.code").value("USER_009"))
875+
.andExpect(jsonPath("$.message").value("탈퇴한 계정입니다."));
876+
}
877+
878+
@Test
879+
@DisplayName("정지된 계정 → 403 Forbidden")
880+
void getMyComments_suspendedUser() throws Exception {
881+
// given
882+
User user = User.createUser("suspended", "[email protected]", passwordEncoder.encode("P@ssw0rd!"));
883+
user.setUserProfile(new UserProfile(user, "닉네임", null, null, null, 0));
884+
user.setUserStatus(UserStatus.SUSPENDED);
885+
userRepository.save(user);
886+
887+
String accessToken = generateAccessToken(user);
888+
889+
// when & then
890+
mvc.perform(get("/api/users/me/comments")
891+
.header("Authorization", "Bearer " + accessToken))
892+
.andDo(print())
893+
.andExpect(status().isForbidden())
894+
.andExpect(jsonPath("$.code").value("USER_008"))
895+
.andExpect(jsonPath("$.message").value("정지된 계정입니다. 관리자에게 문의하세요."));
896+
}
897+
898+
@Test
899+
@DisplayName("AccessToken 없음 → 401 Unauthorized")
900+
void getMyComments_noAccessToken() throws Exception {
901+
// when & then
902+
mvc.perform(get("/api/users/me/comments"))
903+
.andDo(print())
904+
.andExpect(status().isUnauthorized())
905+
.andExpect(jsonPath("$.code").value("AUTH_001"))
906+
.andExpect(jsonPath("$.message").value("인증이 필요합니다."));
907+
}
908+
909+
@Test
910+
@DisplayName("잘못된 AccessToken → 401 Unauthorized")
911+
void getMyComments_invalidAccessToken() throws Exception {
912+
// when & then
913+
mvc.perform(get("/api/users/me/comments")
914+
.header("Authorization", "Bearer invalidToken"))
915+
.andDo(print())
916+
.andExpect(status().isUnauthorized())
917+
.andExpect(jsonPath("$.code").value("AUTH_002"))
918+
.andExpect(jsonPath("$.message").value("유효하지 않은 액세스 토큰입니다."));
919+
}
920+
921+
@Test
922+
@DisplayName("만료된 AccessToken → 401 Unauthorized")
923+
void getMyComments_expiredAccessToken() throws Exception {
924+
// given
925+
User user = User.createUser("expired", "[email protected]", passwordEncoder.encode("P@ssw0rd!"));
926+
user.setUserProfile(new UserProfile(user, "닉네임", null, null, null, 0));
927+
user.setUserStatus(UserStatus.ACTIVE);
928+
userRepository.save(user);
929+
930+
String expiredToken = testJwtTokenProvider.createExpiredAccessToken(user.getId(), user.getUsername(), user.getRole().name());
931+
932+
// when & then
933+
mvc.perform(get("/api/users/me/comments")
934+
.header("Authorization", "Bearer " + expiredToken))
935+
.andDo(print())
936+
.andExpect(status().isUnauthorized())
937+
.andExpect(jsonPath("$.code").value("AUTH_004"))
938+
.andExpect(jsonPath("$.message").value("만료된 액세스 토큰입니다."));
939+
}
798940
}

src/test/java/com/back/domain/user/service/UserServiceTest.java

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.back.domain.user.service;
22

3+
import com.back.domain.board.comment.dto.MyCommentResponse;
4+
import com.back.domain.board.comment.entity.Comment;
5+
import com.back.domain.board.comment.repository.CommentRepository;
36
import com.back.domain.board.common.dto.PageResponse;
47
import com.back.domain.board.post.dto.PostListResponse;
58
import com.back.domain.board.post.entity.Post;
@@ -45,6 +48,9 @@ class UserServiceTest {
4548
@Autowired
4649
private PostRepository postRepository;
4750

51+
@Autowired
52+
private CommentRepository commentRepository;
53+
4854
@Autowired
4955
private PasswordEncoder passwordEncoder;
5056

@@ -445,4 +451,81 @@ void getMyPosts_suspendedUser() {
445451
.isInstanceOf(CustomException.class)
446452
.hasMessage(ErrorCode.USER_SUSPENDED.getMessage());
447453
}
454+
455+
// ====================== 내 댓글 목록 조회 테스트 ======================
456+
457+
@Test
458+
@DisplayName("내 댓글 목록 조회 성공")
459+
void getMyComments_success() {
460+
// given
461+
User user = User.createUser("commenter", "[email protected]", passwordEncoder.encode("P@ssw0rd!"));
462+
user.setUserProfile(new UserProfile(user, "닉네임", null, null, null, 0));
463+
user.setUserStatus(UserStatus.ACTIVE);
464+
userRepository.save(user);
465+
466+
// 게시글 하나 생성
467+
Post post = new Post(user, "테스트 게시글", "게시글 내용", null);
468+
postRepository.save(post);
469+
470+
// 댓글 2개 작성
471+
Comment comment1 = new Comment(post, user, "첫 번째 댓글", null);
472+
Comment comment2 = new Comment(post, user, "두 번째 댓글", null);
473+
commentRepository.saveAll(List.of(comment1, comment2));
474+
475+
Pageable pageable = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "createdAt"));
476+
477+
// when
478+
PageResponse<MyCommentResponse> response = userService.getMyComments(user.getId(), pageable);
479+
480+
// then
481+
assertThat(response.items()).hasSize(2);
482+
assertThat(response.items().get(0).content()).isEqualTo("두 번째 댓글"); // 최신순 정렬
483+
assertThat(response.items().get(1).content()).isEqualTo("첫 번째 댓글");
484+
}
485+
486+
@Test
487+
@DisplayName("존재하지 않는 사용자 ID → USER_NOT_FOUND 예외 발생")
488+
void getMyComments_userNotFound() {
489+
// given
490+
Pageable pageable = PageRequest.of(0, 10);
491+
492+
// when & then
493+
assertThatThrownBy(() -> userService.getMyComments(999L, pageable))
494+
.isInstanceOf(CustomException.class)
495+
.hasMessage(ErrorCode.USER_NOT_FOUND.getMessage());
496+
}
497+
498+
@Test
499+
@DisplayName("탈퇴된 사용자 → USER_DELETED 예외 발생")
500+
void getMyComments_deletedUser() {
501+
// given
502+
User user = User.createUser("deleted", "[email protected]", passwordEncoder.encode("P@ssw0rd!"));
503+
user.setUserProfile(new UserProfile(user, "닉네임", null, null, null, 0));
504+
user.setUserStatus(UserStatus.DELETED);
505+
userRepository.save(user);
506+
507+
Pageable pageable = PageRequest.of(0, 10);
508+
509+
// when & then
510+
assertThatThrownBy(() -> userService.getMyComments(user.getId(), pageable))
511+
.isInstanceOf(CustomException.class)
512+
.hasMessage(ErrorCode.USER_DELETED.getMessage());
513+
}
514+
515+
@Test
516+
@DisplayName("정지된 사용자 → USER_SUSPENDED 예외 발생")
517+
void getMyComments_suspendedUser() {
518+
// given
519+
User user = User.createUser("suspended", "[email protected]", passwordEncoder.encode("P@ssw0rd!"));
520+
user.setUserProfile(new UserProfile(user, "닉네임", null, null, null, 0));
521+
user.setUserStatus(UserStatus.SUSPENDED);
522+
userRepository.save(user);
523+
524+
Pageable pageable = PageRequest.of(0, 10);
525+
526+
// when & then
527+
assertThatThrownBy(() -> userService.getMyComments(user.getId(), pageable))
528+
.isInstanceOf(CustomException.class)
529+
.hasMessage(ErrorCode.USER_SUSPENDED.getMessage());
530+
}
448531
}

0 commit comments

Comments
 (0)