From b9ee06d3c0fcaeb012147b3bb2d8fa199c86a6fa Mon Sep 17 00:00:00 2001 From: ez23re Date: Fri, 8 Nov 2024 23:39:32 +0900 Subject: [PATCH 01/34] =?UTF-8?q?test:=20CommentControllerIntegrationTest?= =?UTF-8?q?=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CommentControllerIntegrationTest.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java index 6cf98a7e..b3556746 100644 --- a/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java @@ -7,7 +7,6 @@ import com.splanet.splanet.comment.repository.CommentRepository; import com.splanet.splanet.comment.service.CommentService; import com.splanet.splanet.core.exception.BusinessException; -import com.splanet.splanet.core.exception.ErrorCode; import com.splanet.splanet.jwt.JwtTokenProvider; import com.splanet.splanet.user.entity.User; import com.splanet.splanet.user.repository.UserRepository; @@ -17,6 +16,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; @@ -198,4 +198,22 @@ void setUp() { .isInstanceOf(BusinessException.class) .hasMessageContaining("댓글을 찾을 수 없습니다.")); } + + @Test + void 댓글_작성_실패_작성자와_댓글달린유저가_같은경우() throws Exception { + CommentRequest commentRequest = new CommentRequest("자기 자신에게 댓글 작성 시도"); + + String sameUserToken = "Bearer " + jwtTokenProvider.createAccessToken(testUser.getId()); + + mockMvc.perform(post("/api/comments") + .header("Authorization", sameUserToken) + .param("writerId", String.valueOf(testUser.getId())) + .param("userId", String.valueOf(testUser.getId())) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(commentRequest))) + .andExpect(status().isBadRequest()) + .andExpect(result -> assertThat(result.getResolvedException()) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("잘못된 요청입니다 (유효하지 않은 댓글 ID).")); + } } \ No newline at end of file From 22613a8358f1006d393ba26e8ef007bc3e12604d Mon Sep 17 00:00:00 2001 From: ez23re Date: Sat, 9 Nov 2024 01:03:15 +0900 Subject: [PATCH 02/34] =?UTF-8?q?test:=20FriendControllerIntegrationTest?= =?UTF-8?q?=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CommentControllerIntegrationTest.java | 1 - .../FriendControllerIntegrationTest.java | 172 ++++++++++++++++++ 2 files changed, 172 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/splanet/splanet/friend/controller/FriendControllerIntegrationTest.java diff --git a/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java index b3556746..00f89a1e 100644 --- a/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java @@ -16,7 +16,6 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; diff --git a/src/test/java/com/splanet/splanet/friend/controller/FriendControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/friend/controller/FriendControllerIntegrationTest.java new file mode 100644 index 00000000..10919df3 --- /dev/null +++ b/src/test/java/com/splanet/splanet/friend/controller/FriendControllerIntegrationTest.java @@ -0,0 +1,172 @@ +package com.splanet.splanet.friend.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.splanet.splanet.friend.dto.FriendResponse; +import com.splanet.splanet.friend.entity.Friend; +import com.splanet.splanet.friend.repository.FriendRepository; +import com.splanet.splanet.friend.service.FriendService; +import com.splanet.splanet.friendRequest.repository.FriendRequestRepository; +import com.splanet.splanet.jwt.JwtTokenProvider; +import com.splanet.splanet.plan.dto.PlanRequestDto; +import com.splanet.splanet.plan.dto.PlanResponseDto; +import com.splanet.splanet.plan.service.PlanService; +import com.splanet.splanet.user.entity.User; +import com.splanet.splanet.user.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +class FriendControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private FriendService friendService; + + @Autowired + private PlanService planService; + + @Autowired + private JwtTokenProvider jwtTokenProvider; + + @Autowired + private FriendRepository friendRepository; + + @Autowired + private FriendRequestRepository friendRequestRepository; + + @Autowired + private UserRepository userRepository; + + private String accessToken; + private Long userId; + + @BeforeEach + void setUp() { + User user = User.builder() + .nickname("testuser") + .profileImage("testimage.png") + .build(); + userRepository.save(user); + userId = user.getId(); + + accessToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); + } + + @Test + @DisplayName("친구 목록 조회 성공") + @WithMockUser + void 친구_목록_조회_성공() throws Exception { + // 친구 목록 조회 결과가 비어 있지 않음을 확인 + List friendResponses = friendService.getFriends(userId); + + // 친구 목록이 비어 있지 않으면 테스트 진행 + if (!friendResponses.isEmpty()) { + mockMvc.perform(get("/api/friends") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].nickname").value(friendResponses.get(0).nickname())) + .andExpect(jsonPath("$[0].profileImage").value(friendResponses.get(0).profileImage())); + } else { + mockMvc.perform(get("/api/friends") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$").isEmpty()); + } + } + + @Test + @DisplayName("친구 목록 조회 실패 - 인증되지 않은 사용자") + void 친구_목록_조회_실패_인증되지않은_사용자() throws Exception { + mockMvc.perform(get("/api/friends") + .header("Authorization", "Bearer invalid-token") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.message").value("유효하지 않은 토큰입니다.")); + } + + @Test + @DisplayName("친구 플랜 조회 실패 - 인증되지 않은 사용자") + void 친구_플랜_조회_실패_인증되지않은_사용자() throws Exception { + Long friendId = 1L; + + mockMvc.perform(get("/api/friends/{friendId}/plans", friendId) + .header("Authorization", "Bearer invalid-token") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.message").value("유효하지 않은 토큰입니다.")); + } + + @Test + @DisplayName("친구 삭제 성공") + @WithMockUser + void 친구_삭제_성공() throws Exception { + // 친구 관계를 만들기 위한 유저 생성 + User friendUser = User.builder() + .nickname("frienduser") + .profileImage("friendimage.png") + .build(); + userRepository.save(friendUser); + + // 기존 userId로 조회하여 친구 관계를 만들기 위해 user 객체를 조회 + User user = userRepository.findById(userId).orElseThrow(); + + // 친구 관계 등록 (예: userId와 friendUserId 사이에 친구 관계가 만들어진다고 가정) + friendRepository.save(new Friend(user, friendUser)); + + mockMvc.perform(delete("/api/friends/{friendId}", friendUser.getId()) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("친구 맺기 취소되었습니다!")); + } + + @Test + @DisplayName("친구 삭제 실패 - 친구가 아님") + @WithMockUser + void 친구_삭제_실패_친구가_아님() throws Exception { + // 존재하지 않는 친구의 ID + Long nonFriendId = 999L; + + mockMvc.perform(delete("/api/friends/{friendId}", nonFriendId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("친구가 아닙니다.")); + } + + @Test + @DisplayName("친구 삭제 실패 - 인증되지 않은 사용자") + void 친구_삭제_실패_인증되지않은_사용자() throws Exception { + // 인증되지 않은 토큰 + mockMvc.perform(delete("/api/friends/{friendId}", 1L) + .header("Authorization", "Bearer invalid-token") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.message").value("유효하지 않은 토큰입니다.")); + } +} \ No newline at end of file From c06620b16483365a62eab10a2feacbaea2739cc3 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sat, 9 Nov 2024 02:17:24 +0900 Subject: [PATCH 03/34] =?UTF-8?q?test:=20FriendRequestControllerIntegratio?= =?UTF-8?q?nTest=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...riendRequestControllerIntegrationTest.java | 261 ++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 src/test/java/com/splanet/splanet/friendRequest/controller/FriendRequestControllerIntegrationTest.java diff --git a/src/test/java/com/splanet/splanet/friendRequest/controller/FriendRequestControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/friendRequest/controller/FriendRequestControllerIntegrationTest.java new file mode 100644 index 00000000..a26132a4 --- /dev/null +++ b/src/test/java/com/splanet/splanet/friendRequest/controller/FriendRequestControllerIntegrationTest.java @@ -0,0 +1,261 @@ +package com.splanet.splanet.friendRequest.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.splanet.splanet.friend.repository.FriendRepository; +import com.splanet.splanet.friendRequest.dto.FriendRequestCreateRequest; +import com.splanet.splanet.friendRequest.entity.FriendRequest; +import com.splanet.splanet.friendRequest.repository.FriendRequestRepository; +import com.splanet.splanet.user.entity.User; +import com.splanet.splanet.user.repository.UserRepository; +import com.splanet.splanet.jwt.JwtTokenProvider; +import jakarta.transaction.Transactional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +class FriendRequestControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private JwtTokenProvider jwtTokenProvider; + + @Autowired + private UserRepository userRepository; + + @Autowired + private FriendRepository friendRepository; + + @Autowired + private FriendRequestRepository friendRequestRepository; + + private String accessToken; + private Long userId; + + @BeforeEach + void setUp() { + User user = User.builder() + .nickname("testuser") + .profileImage("testimage.png") + .build(); + userRepository.save(user); + userId = user.getId(); + + accessToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); + } + + @Test + @WithMockUser + void 친구_요청_실패_본인에게_친구_요청() throws Exception { + FriendRequestCreateRequest request = new FriendRequestCreateRequest(userId); + + mockMvc.perform(post("/api/friends/requests") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("본인에게 친구요청을 보낼 수 없습니다.")); + } + + @Test + @WithMockUser + void 친구_요청_실패_이미_요청한_사용자() throws Exception { + User receiverUser = User.builder() + .nickname("friendUser") + .profileImage("friendImage.png") + .build(); + userRepository.save(receiverUser); + + // 이미 보낸 요청이 있다고 가정 + FriendRequestCreateRequest request = new FriendRequestCreateRequest(receiverUser.getId()); + friendRequestRepository.save(FriendRequest.builder() + .requester(userRepository.findById(userId).orElseThrow()) + .receiver(receiverUser) + .status(FriendRequest.Status.PENDING) + .build()); + + mockMvc.perform(post("/api/friends/requests") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("이미 요청을 보냈습니다.")); + } + + @Test + @WithMockUser + void 친구_요청_실패_존재하지_않는_사용자() throws Exception { + // 존재하지 않는 사용자 ID로 친구 요청 시도 + FriendRequestCreateRequest request = new FriendRequestCreateRequest(999L); + + mockMvc.perform(post("/api/friends/requests") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("유저가 존재하지 않습니다.")); + } + + @Test + @WithMockUser + void 친구_요청_수락_이미_수락된_요청() throws Exception { + // 이미 수락된 친구 요청을 시도 + User receiverUser = User.builder() + .nickname("friendUser") + .profileImage("friendImage.png") + .build(); + userRepository.save(receiverUser); + + User requesterUser = User.builder() + .nickname("requesterUser") + .profileImage("requesterImage.png") + .build(); + userRepository.save(requesterUser); + + // 친구 요청 생성 후 수락 + FriendRequest friendRequest = FriendRequest.builder() + .requester(requesterUser) + .receiver(receiverUser) + .status(FriendRequest.Status.PENDING) + .build(); + friendRequestRepository.save(friendRequest); + + // 친구 요청 수락 + friendRequest.setStatus(FriendRequest.Status.ACCEPTED); + friendRequestRepository.save(friendRequest); + + // 이미 수락된 요청을 다시 수락하려고 시도 + mockMvc.perform(post("/api/friends/requests/{requestId}/accept", friendRequest.getId()) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("이미 수락하거나 거절한 사용자 입니다.")); + } + + @Test + @WithMockUser + void 친구_요청_거절_이미_수락된_요청() throws Exception { + // 이미 수락된 친구 요청을 시도 + User receiverUser = User.builder() + .nickname("friendUser") + .profileImage("friendImage.png") + .build(); + userRepository.save(receiverUser); + + User requesterUser = User.builder() + .nickname("requesterUser") + .profileImage("requesterImage.png") + .build(); + userRepository.save(requesterUser); + + // 친구 요청 생성 후 수락 + FriendRequest friendRequest = FriendRequest.builder() + .requester(requesterUser) + .receiver(receiverUser) + .status(FriendRequest.Status.PENDING) + .build(); + friendRequestRepository.save(friendRequest); + + // 친구 요청 수락 + friendRequest.setStatus(FriendRequest.Status.ACCEPTED); + friendRequestRepository.save(friendRequest); + + // 이미 수락된 요청을 다시 거절하려고 시도 + mockMvc.perform(post("/api/friends/requests/{requestId}/reject", friendRequest.getId()) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("이미 수락하거나 거절한 사용자 입니다.")); + } + + @Test + @WithMockUser + void 친구_요청_취소_성공() throws Exception { + // 친구 요청 생성 (보낸 요청) + User requester = userRepository.findById(userId).orElseThrow(); + User receiver = User.builder() + .nickname("receiver") + .profileImage("receiverImage.png") + .build(); + userRepository.save(receiver); + + FriendRequest friendRequest = FriendRequest.builder() + .requester(requester) + .receiver(receiver) + .status(FriendRequest.Status.PENDING) + .build(); + friendRequestRepository.save(friendRequest); + + // 친구 요청 취소 + mockMvc.perform(delete("/api/friends/requests/{requestId}/cancel", friendRequest.getId()) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("친구 요청이 성공적으로 취소되었습니다.")); + + mockMvc.perform(get("/api/friends/requests/sent") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.size()").value(0)); // 취소되었으므로 보낸 요청 목록에 없음 + } + + @Test + @WithMockUser + void 친구_요청_취소_실패_내가_보낸_요청_아님() throws Exception { + // 친구 요청 생성 (다른 사용자가 보낸 요청) + User requester = User.builder() + .nickname("requester") + .profileImage("requesterImage.png") + .build(); + userRepository.save(requester); + + User receiver = userRepository.findById(userId).orElseThrow(); + FriendRequest friendRequest = FriendRequest.builder() + .requester(requester) + .receiver(receiver) + .status(FriendRequest.Status.PENDING) + .build(); + friendRequestRepository.save(friendRequest); + + // 친구 요청 취소 (다른 사용자가 보낸 요청을 내가 취소하려고 시도) + mockMvc.perform(delete("/api/friends/requests/{requestId}/cancel", friendRequest.getId()) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.message").value("권한이 없습니다.")); + } + + @Test + @WithMockUser + void 친구_요청_취소_실패_존재하지_않는_요청() throws Exception { + // 존재하지 않는 요청 ID로 취소 시도 + mockMvc.perform(delete("/api/friends/requests/{requestId}/cancel", 999L) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("해당 친구 요청을 찾을 수 없습니다.")); + } +} From c2554098b968ebcb38e36f0f2dbe185f107295b5 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sat, 9 Nov 2024 04:26:15 +0900 Subject: [PATCH 04/34] =?UTF-8?q?test:=20CommentAcceptanceTest=20=EC=9E=91?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/CommentAcceptanceTest.java | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/test/java/com/splanet/splanet/comment/controller/CommentAcceptanceTest.java diff --git a/src/test/java/com/splanet/splanet/comment/controller/CommentAcceptanceTest.java b/src/test/java/com/splanet/splanet/comment/controller/CommentAcceptanceTest.java new file mode 100644 index 00000000..6f228f52 --- /dev/null +++ b/src/test/java/com/splanet/splanet/comment/controller/CommentAcceptanceTest.java @@ -0,0 +1,97 @@ +package com.splanet.splanet.comment.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.splanet.splanet.comment.dto.CommentRequest; +import com.splanet.splanet.comment.dto.CommentResponse; +import com.splanet.splanet.comment.service.CommentService; +import com.splanet.splanet.user.entity.User; +import com.splanet.splanet.user.repository.UserRepository; +import com.splanet.splanet.jwt.JwtTokenProvider; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +class CommentAcceptanceTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private JwtTokenProvider jwtTokenProvider; + + @Autowired + private UserRepository userRepository; + + @Autowired + private CommentService commentService; + + private String accessToken; + private Long userId; + private Long writerId; + + @BeforeEach + void setUp() { + User user = User.builder() + .nickname("testuser") + .profileImage("testimage.png") + .build(); + User writer = User.builder() + .nickname("writer") + .profileImage("writerimage.png") + .build(); + userRepository.saveAll(List.of(user, writer)); + userId = user.getId(); + writerId = writer.getId(); + + accessToken = "Bearer " + jwtTokenProvider.createAccessToken(writerId); + } + + @Test + @DisplayName("댓글 작성 실패 - 자기 자신에게 댓글 작성") + void 댓글_작성_실패_자기자신에게_댓글() throws Exception { + CommentRequest request = new CommentRequest("자기 자신에게 댓글 작성"); + + String sameUserToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); + + mockMvc.perform(post("/api/comments") + .header("Authorization", sameUserToken) + .param("writerId", String.valueOf(userId)) + .param("userId", String.valueOf(userId)) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value(containsString("잘못된 요청입니다 (유효하지 않은 댓글 ID)."))); + } + + @Test + @DisplayName("댓글 수정 실패 - 존재하지 않는 댓글 ID") + void 댓글_수정_실패_존재하지않는_댓글() throws Exception { + CommentRequest request = new CommentRequest("수정 실패 댓글"); + + mockMvc.perform(put("/api/comments/9999") + .header("Authorization", accessToken) + .param("userId", String.valueOf(writerId)) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value(containsString("댓글을 찾을 수 없습니다."))); + } +} \ No newline at end of file From eea41382023ad7d6f4deb7417538358ef9951b83 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sat, 9 Nov 2024 04:26:30 +0900 Subject: [PATCH 05/34] =?UTF-8?q?test:=20SubscriptionControllerIntegration?= =?UTF-8?q?Test=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/SubscriptionApi.java | 2 +- ...SubscriptionControllerIntegrationTest.java | 146 ++++++++++++++++++ 2 files changed, 147 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/splanet/splanet/subscription/controller/SubscriptionControllerIntegrationTest.java diff --git a/src/main/java/com/splanet/splanet/subscription/controller/SubscriptionApi.java b/src/main/java/com/splanet/splanet/subscription/controller/SubscriptionApi.java index fd28cec1..1ae30b9a 100644 --- a/src/main/java/com/splanet/splanet/subscription/controller/SubscriptionApi.java +++ b/src/main/java/com/splanet/splanet/subscription/controller/SubscriptionApi.java @@ -43,7 +43,7 @@ ResponseEntity getSubscription( ResponseEntity cancelSubscription( @Parameter(description = "JWT 인증으로 전달된 사용자 ID", required = true) @AuthenticationPrincipal Long userId); - @PostMapping("/payment") + @PostMapping("/subscribe") @Operation(summary = "구독", description = "사용자가 구독을 구매합니다.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "구독이 성공적으로 구매되었습니다.", diff --git a/src/test/java/com/splanet/splanet/subscription/controller/SubscriptionControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/subscription/controller/SubscriptionControllerIntegrationTest.java new file mode 100644 index 00000000..5dc94ff5 --- /dev/null +++ b/src/test/java/com/splanet/splanet/subscription/controller/SubscriptionControllerIntegrationTest.java @@ -0,0 +1,146 @@ +package com.splanet.splanet.subscription.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.splanet.splanet.core.exception.ErrorCode; +import com.splanet.splanet.subscription.dto.SubscriptionRequest; +import com.splanet.splanet.subscription.entity.Subscription; +import com.splanet.splanet.subscription.repository.SubscriptionRepository; +import com.splanet.splanet.user.entity.User; +import com.splanet.splanet.user.repository.UserRepository; +import com.splanet.splanet.jwt.JwtTokenProvider; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +class SubscriptionControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserRepository userRepository; + + @Autowired + private SubscriptionRepository subscriptionRepository; + + @Autowired + private JwtTokenProvider jwtTokenProvider; + + private String token; + private User testUser; + + @BeforeEach + void setUp() { + // 테스트용 유저 생성 + testUser = User.builder() + .nickname("구독 테스트 사용자") + .profileImage("http://example.com/profile.jpg") + .kakaoId(123456789L) + .isPremium(false) + .build(); + userRepository.save(testUser); + + // JWT 토큰 생성 + token = "Bearer " + jwtTokenProvider.createAccessToken(testUser.getId()); + } + + @Test + void 구독_생성_성공() throws Exception { + // Given + SubscriptionRequest request = new SubscriptionRequest(); + request.setType(Subscription.Type.MONTHLY); + + // When & Then + mockMvc.perform(post("/api/subscription/me/subscribe") + .header("Authorization", token) + .contentType(MediaType.APPLICATION_JSON) + .content(new ObjectMapper().writeValueAsString(request))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("구독이 성공적으로 완료되었습니다.")) + .andExpect(jsonPath("$.subscription.id").exists()) + .andExpect(jsonPath("$.subscription.startDate").exists()) + .andExpect(jsonPath("$.subscription.endDate").doesNotExist()); + + // 데이터베이스에 구독 정보가 저장되었는지 확인 + Subscription newSubscription = subscriptionRepository.findTopByUserIdAndStatusOrderByStartDateDesc(testUser.getId(), Subscription.Status.ACTIVE) + .orElseThrow(() -> new AssertionError("구독 정보가 저장되지 않았습니다.")); + + assertThat(newSubscription.getType()).isEqualTo(request.getType()); + assertThat(newSubscription.getStatus()).isEqualTo(Subscription.Status.ACTIVE); + } + + @Test + void 구독_생성_실패_이미_구독중() throws Exception { + // Given + Subscription existingSubscription = Subscription.builder() + .user(testUser) + .status(Subscription.Status.ACTIVE) + .type(Subscription.Type.MONTHLY) + .startDate(LocalDateTime.now()) + .endDate(LocalDateTime.now().plusMonths(1)) + .build(); + subscriptionRepository.save(existingSubscription); + + // When & Then + SubscriptionRequest request = new SubscriptionRequest(); + request.setType(Subscription.Type.MONTHLY); + + mockMvc.perform(post("/api/subscription/me/subscribe") + .header("Authorization", token) + .contentType(MediaType.APPLICATION_JSON) + .content(new ObjectMapper().writeValueAsString(request))) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value(ErrorCode.ALREADY_SUBSCRIBED.getMessage())) + .andExpect(jsonPath("$.status").value(ErrorCode.ALREADY_SUBSCRIBED.getStatus().value())); + } + + @Test + void 구독_정보_조회_성공() throws Exception { + // Given + Subscription subscription = Subscription.builder() + .user(testUser) + .type(Subscription.Type.MONTHLY) + .startDate(LocalDateTime.now()) + .endDate(LocalDateTime.now().plusMonths(1)) + .build(); + subscriptionRepository.save(subscription); + + // When & Then + mockMvc.perform(get("/api/subscription/me") + .header("Authorization", token) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("구독 정보가 성공적으로 조회되었습니다.")) + .andExpect(jsonPath("$.subscription.id").exists()) + .andExpect(jsonPath("$.subscription.startDate").exists()) + .andExpect(jsonPath("$.subscription.endDate").exists()); + } + + @Test + void 구독_정보_조회_실패_구독없음() throws Exception { + // Given + + // When & Then + mockMvc.perform(get("/api/subscriptions/me") + .header("Authorization", "Bearer ") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()); + } +} \ No newline at end of file From 431d92dc2f24088748053fd7a88058c608b9dfbf Mon Sep 17 00:00:00 2001 From: ez23re Date: Sat, 9 Nov 2024 20:16:32 +0900 Subject: [PATCH 06/34] =?UTF-8?q?test:=20PaymentControllerIntegrationTest?= =?UTF-8?q?=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PaymentControllerIntegrationTest.java | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 src/test/java/com/splanet/splanet/payment/controller/PaymentControllerIntegrationTest.java diff --git a/src/test/java/com/splanet/splanet/payment/controller/PaymentControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/payment/controller/PaymentControllerIntegrationTest.java new file mode 100644 index 00000000..5ddff179 --- /dev/null +++ b/src/test/java/com/splanet/splanet/payment/controller/PaymentControllerIntegrationTest.java @@ -0,0 +1,142 @@ +package com.splanet.splanet.payment.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.splanet.splanet.jwt.JwtTokenProvider; +import com.splanet.splanet.payment.entity.Payment; +import com.splanet.splanet.payment.repository.PaymentRepository; +import com.splanet.splanet.subscription.entity.Subscription; +import com.splanet.splanet.subscription.repository.SubscriptionRepository; +import com.splanet.splanet.user.entity.User; +import com.splanet.splanet.user.repository.UserRepository; +import jakarta.transaction.Transactional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import java.time.LocalDateTime; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +public class PaymentControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private UserRepository userRepository; + + @Autowired + private JwtTokenProvider jwtTokenProvider; + + @Autowired + private PaymentRepository paymentRepository; + + @Autowired + private SubscriptionRepository subscriptionRepository; + + private User testUser; + private String token; + private Subscription testSubscription; + private Payment testPayment; + + @BeforeEach + void setUp() { + // 테스트용 유저 생성 + testUser = User.builder() + .nickname("테스트유저") + .profileImage("http://example.com/profile.jpg") + .kakaoId(123456789L) + .isPremium(false) + .build(); + userRepository.save(testUser); + + // JWT 토큰 생성 + token = "Bearer " + jwtTokenProvider.createAccessToken(testUser.getId()); + + // 테스트용 Subscription 생성 + testSubscription = Subscription.builder() + .user(testUser) + .status(Subscription.Status.ACTIVE) + .type(Subscription.Type.MONTHLY) + .startDate(LocalDateTime.now()) + .endDate(LocalDateTime.now().plusMonths(1)) + .build(); + subscriptionRepository.save(testSubscription); + + // Payment 생성 + testPayment = Payment.builder() + .price(1000) + .status(Payment.Status.PENDING) + .paymentDate(LocalDateTime.now()) + .subscription(testSubscription) + .build(); + paymentRepository.save(testPayment); + } + + @Test + public void 결제상태조회_존재하지않는_결제ID_실패() throws Exception { + // given + Long invalidPaymentId = 999L; + + // when & then + mockMvc.perform(get("/api/payment/{paymentId}", invalidPaymentId) + .header("Authorization", token) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("결제 정보가 존재하지 않습니다.")) + .andExpect(jsonPath("$.status").value("404")); + } + + @Test + public void 결제삭제_성공() throws Exception { + // given + Long validPaymentId = testPayment.getId(); + Long validUserId = testPayment.getSubscription().getUser().getId(); + + // when & then + mockMvc.perform(MockMvcRequestBuilders.delete("/api/payment/{paymentId}", validPaymentId) + .header("Authorization", token) + .param("userId", validUserId.toString())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.message").value("결제가 성공적으로 삭제되었습니다.")); + } + + @Test + public void 결제삭제_결제없음_실패() throws Exception { + // given + Long invalidPaymentId = 999L; + + // when & then + mockMvc.perform(MockMvcRequestBuilders.delete("/api/payment/{paymentId}", invalidPaymentId) + .header("Authorization", token)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("결제 정보가 존재하지 않습니다.")) + .andExpect(jsonPath("$.status").value("404")); + } + + @Test + public void 결제삭제_다른유저의_결제정보접근_실패() throws Exception { + Long validPaymentId = testPayment.getId(); + Long invalidUserId = 123L; + String invalidToken = jwtTokenProvider.createAccessToken(invalidUserId); + + mockMvc.perform(MockMvcRequestBuilders.delete("/api/payment/{paymentId}", validPaymentId) + .header("Authorization", "Bearer " + invalidToken)) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.message").value("다른 유저의 결제 정보에 접근할 수 없습니다.")) + .andExpect(jsonPath("$.status").value("401")); + } +} \ No newline at end of file From 1915317eb0eee2cbc7efcf21f2a641726a708f72 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sat, 9 Nov 2024 23:25:14 +0900 Subject: [PATCH 07/34] =?UTF-8?q?refactor:=20TeamPlanController=20@Overrid?= =?UTF-8?q?e=EB=A1=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../teamplan/controller/TeamPlanController.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/splanet/splanet/teamplan/controller/TeamPlanController.java b/src/main/java/com/splanet/splanet/teamplan/controller/TeamPlanController.java index 69db352a..2857565b 100644 --- a/src/main/java/com/splanet/splanet/teamplan/controller/TeamPlanController.java +++ b/src/main/java/com/splanet/splanet/teamplan/controller/TeamPlanController.java @@ -17,7 +17,7 @@ public class TeamPlanController implements TeamPlanApi{ private final TeamPlanService teamPlanService; // 팀 플랜 생성 - @PostMapping + @Override public ResponseEntity createTeamPlan( @AuthenticationPrincipal Long userId, @PathVariable Long teamId, @@ -27,7 +27,7 @@ public ResponseEntity createTeamPlan( } // 팀 플랜 조회 - @GetMapping("/{planId}") + @Override public ResponseEntity getTeamPlan( @PathVariable Long teamId, @PathVariable Long planId) { @@ -36,14 +36,14 @@ public ResponseEntity getTeamPlan( } // 팀의 모든 플랜 조회 - @GetMapping + @Override public ResponseEntity> getAllTeamPlans(@PathVariable Long teamId) { List plans = teamPlanService.getAllTeamPlans(teamId); return ResponseEntity.ok(plans); } // 팀 플랜 수정 - @PutMapping("/{planId}") + @Override public ResponseEntity updateTeamPlan( @AuthenticationPrincipal Long userId, @PathVariable Long teamId, @@ -54,7 +54,7 @@ public ResponseEntity updateTeamPlan( } // 팀 플랜 삭제 - @DeleteMapping("/{planId}") + @Override public ResponseEntity deleteTeamPlan( @AuthenticationPrincipal Long userId, @PathVariable Long teamId, From 11a1e617337039d28bfd253f6a304bb3abc92add Mon Sep 17 00:00:00 2001 From: ez23re Date: Sat, 9 Nov 2024 23:27:00 +0900 Subject: [PATCH 08/34] =?UTF-8?q?refactor:=20=EA=B2=BD=EB=A1=9C=20?= =?UTF-8?q?=EC=9D=B4=EC=83=81=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/splanet/splanet/team/controller/TeamApi.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/splanet/splanet/team/controller/TeamApi.java b/src/main/java/com/splanet/splanet/team/controller/TeamApi.java index 6eec3798..a7eaa2e0 100644 --- a/src/main/java/com/splanet/splanet/team/controller/TeamApi.java +++ b/src/main/java/com/splanet/splanet/team/controller/TeamApi.java @@ -1,4 +1,4 @@ -package com.splanet.splanet.team.api; +package com.splanet.splanet.team.controller; import com.splanet.splanet.team.dto.TeamDto; import com.splanet.splanet.team.dto.TeamInvitationDto; From 28cc824a1dfe8da4f5641d07dc1e3bbc302b0a74 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 00:12:20 +0900 Subject: [PATCH 09/34] =?UTF-8?q?test:=20CommentControllerIntegrationTest?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CommentControllerIntegrationTest.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java index 00f89a1e..faa2d439 100644 --- a/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java @@ -215,4 +215,32 @@ void setUp() { .isInstanceOf(BusinessException.class) .hasMessageContaining("잘못된 요청입니다 (유효하지 않은 댓글 ID).")); } + + @Test + void 댓글_조회_특정_유저() throws Exception { + // testUser가 작성한 댓글 추가 + Comment comment = Comment.builder() + .user(testUser) + .writer(writerUser) + .content("testUser의 댓글") + .build(); + commentRepository.save(comment); + + // testUser의 댓글만 조회하는 API 요청 + mockMvc.perform(get("/api/comments/{userId}", testUser.getId()) + .header("Authorization", token)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.length()").value(1)) + .andExpect(jsonPath("$[0].content").value("testUser의 댓글")); + } + + @Test + void 댓글_조회_존재하지_않는_댓글() throws Exception { + Long nonExistentCommentId = 999L; + + mockMvc.perform(get("/api/comments/{id}", nonExistentCommentId) + .header("Authorization", token)) + .andExpect(status().isOk()) + .andExpect(content().json("[]")); + } } \ No newline at end of file From 6f06d366cc058fb6e9fb37c24737d0571a473880 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 00:23:22 +0900 Subject: [PATCH 10/34] =?UTF-8?q?test:=20FriendControllerIntegrationTest?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/FriendControllerIntegrationTest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/test/java/com/splanet/splanet/friend/controller/FriendControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/friend/controller/FriendControllerIntegrationTest.java index 10919df3..efa981ce 100644 --- a/src/test/java/com/splanet/splanet/friend/controller/FriendControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/friend/controller/FriendControllerIntegrationTest.java @@ -169,4 +169,16 @@ void setUp() { .andExpect(status().isForbidden()) .andExpect(jsonPath("$.message").value("유효하지 않은 토큰입니다.")); } + + @Test + @WithMockUser + void 친구_플랜_조회_실패_친구가_아님() throws Exception { + Long nonFriendId = 999L; + + mockMvc.perform(get("/api/friends/{friendId}/plans", nonFriendId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("친구가 아닙니다.")); + } } \ No newline at end of file From ce607a43199c6d1e17b62bd121c0edf3243ab16b Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 00:23:50 +0900 Subject: [PATCH 11/34] =?UTF-8?q?refactor:=20=EA=B2=BD=EB=A1=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/splanet/splanet/team/controller/TeamController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/splanet/splanet/team/controller/TeamController.java b/src/main/java/com/splanet/splanet/team/controller/TeamController.java index 2d598df9..8d052670 100644 --- a/src/main/java/com/splanet/splanet/team/controller/TeamController.java +++ b/src/main/java/com/splanet/splanet/team/controller/TeamController.java @@ -1,6 +1,6 @@ package com.splanet.splanet.team.controller; -import com.splanet.splanet.team.api.TeamApi; +import com.splanet.splanet.team.controller.TeamApi; import com.splanet.splanet.team.dto.TeamDto; import com.splanet.splanet.team.dto.TeamInvitationDto; import com.splanet.splanet.team.dto.TeamMemberDto; From 2ec5da85ae52507caae86d7a9c771faf2e58cc24 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 00:34:21 +0900 Subject: [PATCH 12/34] =?UTF-8?q?test:=20FriendRequestControllerIntegratio?= =?UTF-8?q?nTest=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...riendRequestControllerIntegrationTest.java | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/splanet/splanet/friendRequest/controller/FriendRequestControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/friendRequest/controller/FriendRequestControllerIntegrationTest.java index a26132a4..39544bfc 100644 --- a/src/test/java/com/splanet/splanet/friendRequest/controller/FriendRequestControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/friendRequest/controller/FriendRequestControllerIntegrationTest.java @@ -120,7 +120,7 @@ void setUp() { @Test @WithMockUser - void 친구_요청_수락_이미_수락된_요청() throws Exception { + void 친구_요청_수락_실패_이미_수락된_요청() throws Exception { // 이미 수락된 친구 요청을 시도 User receiverUser = User.builder() .nickname("friendUser") @@ -156,7 +156,7 @@ void setUp() { @Test @WithMockUser - void 친구_요청_거절_이미_수락된_요청() throws Exception { + void 친구_요청_거절_실패_이미_수락된_요청() throws Exception { // 이미 수락된 친구 요청을 시도 User receiverUser = User.builder() .nickname("friendUser") @@ -258,4 +258,24 @@ void setUp() { .andExpect(status().isNotFound()) .andExpect(jsonPath("$.message").value("해당 친구 요청을 찾을 수 없습니다.")); } -} + + @Test + @WithMockUser + void 친구_요청_목록_조회_성공_받은_요청() throws Exception { + mockMvc.perform(get("/api/friends/requests/received") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$").isArray()); + } + + @Test + @WithMockUser + void 친구_요청_목록_조회_성공_보낸_요청() throws Exception { + mockMvc.perform(get("/api/friends/requests/sent") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$").isArray()); + } +} \ No newline at end of file From 5f2ce2a1ab17e4cc687ac793204a2e2accfe2b77 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 14:39:13 +0900 Subject: [PATCH 13/34] =?UTF-8?q?refactor:=20=ED=8C=80=EC=9D=B4=EB=A6=84?= =?UTF-8?q?=20null=EC=9D=BC=20=EA=B2=BD=EC=9A=B0=20=EC=97=90=EB=9F=AC?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EB=B3=B4=EC=99=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/splanet/splanet/core/exception/ErrorCode.java | 1 + src/main/java/com/splanet/splanet/team/service/TeamService.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/splanet/splanet/core/exception/ErrorCode.java b/src/main/java/com/splanet/splanet/core/exception/ErrorCode.java index 9ed92347..347ef529 100644 --- a/src/main/java/com/splanet/splanet/core/exception/ErrorCode.java +++ b/src/main/java/com/splanet/splanet/core/exception/ErrorCode.java @@ -37,6 +37,7 @@ public enum ErrorCode { INVITATION_NOT_FOUND("초대를 찾을 수 없습니다.", HttpStatus.NOT_FOUND), INVITATION_ALREADY_PROCESSED("초대가 이미 처리되었습니다.", HttpStatus.BAD_REQUEST), USER_ALREADY_IN_TEAM("해당 유저는 이미 팀에 속해 있습니다.", HttpStatus.BAD_REQUEST), + TEAM_NAME_NOT_FOUND("팀이름이 비어 있습니다.", HttpStatus.NOT_FOUND), // friend FRIEND_NOT_FOUND("친구가 아닙니다.",HttpStatus.NOT_FOUND), diff --git a/src/main/java/com/splanet/splanet/team/service/TeamService.java b/src/main/java/com/splanet/splanet/team/service/TeamService.java index e401f845..4af5b483 100644 --- a/src/main/java/com/splanet/splanet/team/service/TeamService.java +++ b/src/main/java/com/splanet/splanet/team/service/TeamService.java @@ -39,7 +39,7 @@ public TeamService(TeamRepository teamRepository, UserRepository userRepository, @Transactional public TeamDto createTeam(String teamName, Long userId) { if (teamName == null || teamName.isBlank()) { - throw new BusinessException(ErrorCode.INVALID_INPUT_VALUE); + throw new BusinessException(ErrorCode.TEAM_NAME_NOT_FOUND); } User user = findUserById(userId); From c05fd7f9f680037da8962ad818b099a10924663b Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 14:50:50 +0900 Subject: [PATCH 14/34] =?UTF-8?q?refactor:=20=EC=9B=90=EB=9E=98=EB=8C=80?= =?UTF-8?q?=EB=A1=9C=20=EB=B3=B8=EC=9D=B8=EC=97=90=EA=B2=8C=20=EB=8C=93?= =?UTF-8?q?=EA=B8=80=20=EB=8B=AC=20=EC=88=98=20=EC=9E=88=EB=8F=84=EB=A1=9D?= =?UTF-8?q?=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../splanet/splanet/comment/controller/CommentApi.java | 3 +-- .../splanet/comment/controller/CommentController.java | 4 ++-- .../splanet/splanet/comment/dto/CommentRequest.java | 2 +- .../splanet/comment/service/CommentService.java | 10 +++------- 4 files changed, 7 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/splanet/splanet/comment/controller/CommentApi.java b/src/main/java/com/splanet/splanet/comment/controller/CommentApi.java index 8926248d..fbe8ecef 100644 --- a/src/main/java/com/splanet/splanet/comment/controller/CommentApi.java +++ b/src/main/java/com/splanet/splanet/comment/controller/CommentApi.java @@ -44,8 +44,7 @@ ResponseEntity> getComments( content = @Content(schema = @Schema(implementation = ErrorResponse.class))) }) ResponseEntity createComment( - @Parameter(description = "작성자(인증된 유저)의 ID", required = true) @AuthenticationPrincipal Long writerId, - @Parameter(description = "대상 유저의 ID", required = true) @RequestParam Long userId, + @Parameter(description = "인증된 유저의 ID", required = true) @AuthenticationPrincipal Long userId, @Parameter(description = "댓글 작성 요청 정보", required = true) @RequestBody CommentRequest request); @PutMapping("/{commentId}") diff --git a/src/main/java/com/splanet/splanet/comment/controller/CommentController.java b/src/main/java/com/splanet/splanet/comment/controller/CommentController.java index c850fae4..ca807ded 100644 --- a/src/main/java/com/splanet/splanet/comment/controller/CommentController.java +++ b/src/main/java/com/splanet/splanet/comment/controller/CommentController.java @@ -22,8 +22,8 @@ public ResponseEntity> getComments(Long userId, Long userI } @Override - public ResponseEntity createComment(Long writerId, Long userId, CommentRequest request) { - commentService.createComment(writerId, userId, request); + public ResponseEntity createComment(Long userId, CommentRequest request) { + commentService.createComment(userId, request); return ResponseEntity.ok("댓글이 성공적으로 작성되었습니다."); } diff --git a/src/main/java/com/splanet/splanet/comment/dto/CommentRequest.java b/src/main/java/com/splanet/splanet/comment/dto/CommentRequest.java index df2afed8..0cfe04cd 100644 --- a/src/main/java/com/splanet/splanet/comment/dto/CommentRequest.java +++ b/src/main/java/com/splanet/splanet/comment/dto/CommentRequest.java @@ -1,4 +1,4 @@ package com.splanet.splanet.comment.dto; -public record CommentRequest(String content) { +public record CommentRequest(Long userId, String content) { } \ No newline at end of file diff --git a/src/main/java/com/splanet/splanet/comment/service/CommentService.java b/src/main/java/com/splanet/splanet/comment/service/CommentService.java index cab73be0..ef315d45 100644 --- a/src/main/java/com/splanet/splanet/comment/service/CommentService.java +++ b/src/main/java/com/splanet/splanet/comment/service/CommentService.java @@ -31,16 +31,12 @@ public List getComments(Long userId) { // 댓글 작성 @Transactional - public void createComment(Long writerId, Long userId, CommentRequest request) { - User user = userRepository.findById(userId) + public void createComment(Long userId, CommentRequest request) { + User user = userRepository.findById(request.userId()) .orElseThrow(() -> new BusinessException(ErrorCode.USER_NOT_FOUND)); - User writer = userRepository.findById(writerId) + User writer = userRepository.findById(userId) .orElseThrow(() -> new BusinessException(ErrorCode.USER_NOT_FOUND)); - if (user.getId().equals(writer.getId())) { - throw new BusinessException(ErrorCode.INVALID_COMMENT_ID); - } - Comment comment = Comment.builder() .user(user) .writer(writer) From 0853d8182666bf012182d567f4cd977b1120a0ba Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 15:05:29 +0900 Subject: [PATCH 15/34] =?UTF-8?q?test:=20=EA=B7=B8=EC=97=90=20=EB=A7=9E?= =?UTF-8?q?=EA=B2=8C=20=EB=8C=93=EA=B8=80=20=EB=8B=A8=EC=9C=84=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../comment/service/CommentServiceTest.java | 43 +++++++++++-------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/src/test/java/com/splanet/splanet/comment/service/CommentServiceTest.java b/src/test/java/com/splanet/splanet/comment/service/CommentServiceTest.java index b1b79c91..3923f0e0 100644 --- a/src/test/java/com/splanet/splanet/comment/service/CommentServiceTest.java +++ b/src/test/java/com/splanet/splanet/comment/service/CommentServiceTest.java @@ -5,7 +5,6 @@ import com.splanet.splanet.comment.entity.Comment; import com.splanet.splanet.comment.repository.CommentRepository; import com.splanet.splanet.core.exception.BusinessException; -import com.splanet.splanet.core.exception.ErrorCode; import com.splanet.splanet.user.entity.User; import com.splanet.splanet.user.repository.UserRepository; import org.junit.jupiter.api.BeforeEach; @@ -45,7 +44,7 @@ void setUp() { Comment comment = Comment.builder() .id(1L) .writer(user) - .content("테스트 댓글") + .content("test content") .user(user) .build(); when(commentRepository.findByUserId(anyLong())).thenReturn(List.of(comment)); @@ -55,7 +54,17 @@ void setUp() { // then assertEquals(1, responses.size()); - assertEquals("테스트 댓글", responses.get(0).content()); + assertEquals("test content", responses.get(0).content()); + } + + @Test + void 댓글조회_사용자없음() { + // given + when(commentRepository.findByUserId(anyLong())).thenReturn(List.of()); + + // when & then + List responses = commentService.getComments(99L); + assertEquals(0, responses.size()); } @Test @@ -63,51 +72,49 @@ void setUp() { // given User user = User.builder().id(1L).build(); User writer = User.builder().id(2L).build(); - CommentRequest request = new CommentRequest("테스트 댓글 내용"); + CommentRequest request = new CommentRequest(1L, "test content"); when(userRepository.findById(1L)).thenReturn(Optional.of(user)); when(userRepository.findById(2L)).thenReturn(Optional.of(writer)); when(commentRepository.save(any(Comment.class))).thenReturn(Comment.builder().id(1L).build()); // when - commentService.createComment(2L, 1L, request); + commentService.createComment(2L, request); // then verify(commentRepository, times(1)).save(any(Comment.class)); } @Test - void 댓글작성_본인에게댓글달때_실패() { + void 댓글작성_사용자없음() { // given - User user = User.builder().id(1L).build(); - CommentRequest request = new CommentRequest("자기 자신에게 댓글을 달려고 합니다."); - when(userRepository.findById(1L)).thenReturn(Optional.of(user)); + CommentRequest request = new CommentRequest(1L, "test content"); + when(userRepository.findById(1L)).thenReturn(Optional.empty()); // when & then - BusinessException exception = assertThrows(BusinessException.class, () -> commentService.createComment(1L, 1L, request)); - assertEquals(ErrorCode.INVALID_COMMENT_ID, exception.getErrorCode()); + assertThrows(BusinessException.class, () -> commentService.createComment(2L, request)); } @Test void 댓글수정성공() { // given User writer = User.builder().id(2L).build(); - Comment comment = Comment.builder().id(1L).writer(writer).content("기존 내용").build(); - CommentRequest request = new CommentRequest("새로운 내용"); + Comment comment = Comment.builder().id(1L).writer(writer).content("old content").build(); + CommentRequest request = new CommentRequest(1L, "new content"); when(commentRepository.findById(1L)).thenReturn(Optional.of(comment)); // when commentService.updateComment(1L, request, 2L); // then - assertEquals("새로운 내용", comment.getContent()); + assertEquals("new content", comment.getContent()); } @Test - void 댓글수정_작성자불일치_실패() { + void 댓글수정_작성자불일치() { // given User writer = User.builder().id(2L).build(); - Comment comment = Comment.builder().id(1L).writer(writer).content("기존 내용").build(); - CommentRequest request = new CommentRequest("새로운 내용"); + Comment comment = Comment.builder().id(1L).writer(writer).content("old content").build(); + CommentRequest request = new CommentRequest(1L, "new content"); when(commentRepository.findById(1L)).thenReturn(Optional.of(comment)); // when & then @@ -129,7 +136,7 @@ void setUp() { } @Test - void 댓글삭제_작성자불일치_실패() { + void 댓글삭제_작성자불일치() { // given User writer = User.builder().id(2L).build(); Comment comment = Comment.builder().id(1L).writer(writer).build(); From 41621d4be34fc1d187e57423f7e5b300b20e888c Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 15:45:32 +0900 Subject: [PATCH 16/34] =?UTF-8?q?test:=20=EB=8C=93=EA=B8=80api=20=ED=86=B5?= =?UTF-8?q?=ED=95=A9=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EB=B3=B4=EC=99=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CommentControllerIntegrationTest.java | 131 +++++++++--------- 1 file changed, 62 insertions(+), 69 deletions(-) diff --git a/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java index faa2d439..268e149c 100644 --- a/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/comment/controller/CommentControllerIntegrationTest.java @@ -16,6 +16,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; @@ -101,14 +102,41 @@ void setUp() { assertThat(comments.get(0).content()).isEqualTo("testUser의 댓글"); } + @Test + void 댓글_조회_특정_유저() throws Exception { + // testUser가 작성한 댓글 추가 + Comment comment = Comment.builder() + .user(testUser) + .writer(writerUser) + .content("testUser의 댓글") + .build(); + commentRepository.save(comment); + + // testUser의 댓글만 조회하는 API 요청 + mockMvc.perform(get("/api/comments/{userId}", testUser.getId()) + .header("Authorization", token)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.length()").value(1)) + .andExpect(jsonPath("$[0].content").value("testUser의 댓글")); + } + + @Test + void 댓글_조회_존재하지_않는_댓글() throws Exception { + Long nonExistentCommentId = 999L; + + mockMvc.perform(get("/api/comments/{id}", nonExistentCommentId) + .header("Authorization", token)) + .andExpect(status().isOk()) + .andExpect(content().json("[]")); + } + @Test void 댓글_작성_성공() throws Exception { - CommentRequest commentRequest = new CommentRequest("새로운 댓글 내용"); + // CommentRequest에서 userId와 content만 전달하도록 수정 + CommentRequest commentRequest = new CommentRequest(testUser.getId(), "새로운 댓글 내용"); mockMvc.perform(post("/api/comments") .header("Authorization", token) - .param("writerId", String.valueOf(writerUser.getId())) - .param("userId", String.valueOf(testUser.getId())) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(commentRequest))) .andExpect(status().isOk()) @@ -120,13 +148,28 @@ void setUp() { assertThat(comments.get(0).getContent()).isEqualTo("새로운 댓글 내용"); } + @Test + void 댓글_작성_실패_존재하지않은_사용자ID() throws Exception { + // 존재하지 않는 userId로 댓글 작성 요청 + Long invalidUserId = 999L; + CommentRequest commentRequest = new CommentRequest(invalidUserId, "존재하지않는 userId로 댓글 작성 시도"); + + mockMvc.perform(post("/api/comments") + .header("Authorization", token) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(commentRequest))) + .andExpect(status().isNotFound()) + .andExpect(result -> assertThat(result.getResolvedException()) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("유저가 존재하지 않습니다.")); + } + @Test void 댓글_수정_성공() throws Exception { - CommentRequest updatedRequest = new CommentRequest("수정된 댓글 내용"); + CommentRequest updatedRequest = new CommentRequest(testUser.getId(), "수정된 댓글 내용"); mockMvc.perform(put("/api/comments/" + testComment.getId()) .header("Authorization", token) - .param("userId", String.valueOf(writerUser.getId())) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(updatedRequest))) .andExpect(status().isOk()) @@ -137,27 +180,14 @@ void setUp() { assertThat(updatedComment.getContent()).isEqualTo("수정된 댓글 내용"); } - @Test - void 댓글_삭제_성공() throws Exception { - mockMvc.perform(delete("/api/comments/" + testComment.getId()) - .header("Authorization", token) - .param("userId", String.valueOf(writerUser.getId()))) - .andExpect(status().isOk()) - .andExpect(content().string("댓글이 성공적으로 삭제되었습니다.")); - - // 댓글이 실제로 삭제되었는지 확인 - assertThat(commentRepository.findById(testComment.getId())).isEmpty(); - } - @Test void 댓글_수정_실패_작성자가_아님() throws Exception { - CommentRequest updatedRequest = new CommentRequest("권한 없는 사용자의 수정 시도"); + CommentRequest updatedRequest = new CommentRequest(testUser.getId(), "권한 없는 사용자의 수정 시도"); String unauthorizedToken = "Bearer " + jwtTokenProvider.createAccessToken(testUser.getId()); mockMvc.perform(put("/api/comments/" + testComment.getId()) .header("Authorization", unauthorizedToken) - .param("userId", String.valueOf(testUser.getId())) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(updatedRequest))) .andExpect(status().isForbidden()) @@ -168,14 +198,13 @@ void setUp() { @Test void 댓글_수정_실패_존재하지_않는_댓글() throws Exception { - CommentRequest updatedRequest = new CommentRequest("수정된 댓글 내용"); + CommentRequest updatedRequest = new CommentRequest(testUser.getId(), "수정된 댓글 내용"); // 존재하지 않는 댓글 ID로 수정 요청 Long nonExistentCommentId = 999L; mockMvc.perform(put("/api/comments/" + nonExistentCommentId) .header("Authorization", token) - .param("userId", String.valueOf(writerUser.getId())) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(updatedRequest))) .andExpect(status().isNotFound()) @@ -184,63 +213,27 @@ void setUp() { .hasMessageContaining("댓글을 찾을 수 없습니다.")); } + @Test + void 댓글_삭제_성공() throws Exception { + mockMvc.perform(delete("/api/comments/" + testComment.getId()) + .header("Authorization", token)) + .andExpect(status().isOk()) + .andExpect(content().string("댓글이 성공적으로 삭제되었습니다.")); + + // 댓글이 실제로 삭제되었는지 확인 + assertThat(commentRepository.findById(testComment.getId())).isEmpty(); + } + @Test void 댓글_삭제_실패_존재하지_않는_댓글() throws Exception { // 존재하지 않는 댓글 ID로 삭제 요청 Long nonExistentCommentId = 999L; mockMvc.perform(delete("/api/comments/" + nonExistentCommentId) - .header("Authorization", token) - .param("userId", String.valueOf(writerUser.getId()))) + .header("Authorization", token)) .andExpect(status().isNotFound()) .andExpect(result -> assertThat(result.getResolvedException()) .isInstanceOf(BusinessException.class) .hasMessageContaining("댓글을 찾을 수 없습니다.")); } - - @Test - void 댓글_작성_실패_작성자와_댓글달린유저가_같은경우() throws Exception { - CommentRequest commentRequest = new CommentRequest("자기 자신에게 댓글 작성 시도"); - - String sameUserToken = "Bearer " + jwtTokenProvider.createAccessToken(testUser.getId()); - - mockMvc.perform(post("/api/comments") - .header("Authorization", sameUserToken) - .param("writerId", String.valueOf(testUser.getId())) - .param("userId", String.valueOf(testUser.getId())) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(commentRequest))) - .andExpect(status().isBadRequest()) - .andExpect(result -> assertThat(result.getResolvedException()) - .isInstanceOf(BusinessException.class) - .hasMessageContaining("잘못된 요청입니다 (유효하지 않은 댓글 ID).")); - } - - @Test - void 댓글_조회_특정_유저() throws Exception { - // testUser가 작성한 댓글 추가 - Comment comment = Comment.builder() - .user(testUser) - .writer(writerUser) - .content("testUser의 댓글") - .build(); - commentRepository.save(comment); - - // testUser의 댓글만 조회하는 API 요청 - mockMvc.perform(get("/api/comments/{userId}", testUser.getId()) - .header("Authorization", token)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.length()").value(1)) - .andExpect(jsonPath("$[0].content").value("testUser의 댓글")); - } - - @Test - void 댓글_조회_존재하지_않는_댓글() throws Exception { - Long nonExistentCommentId = 999L; - - mockMvc.perform(get("/api/comments/{id}", nonExistentCommentId) - .header("Authorization", token)) - .andExpect(status().isOk()) - .andExpect(content().json("[]")); - } } \ No newline at end of file From 5e995f67525fa1ec20c9c42fc5bf6e2b9d5843f6 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 16:32:30 +0900 Subject: [PATCH 17/34] =?UTF-8?q?test:=20=ED=94=84=EB=A6=AC=ED=93=A8?= =?UTF-8?q?=EB=A5=BC=EB=9E=9C=20=ED=86=B5=ED=95=A9=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=A1=B0=ED=9A=8C,=EC=83=9D=EC=84=B1=20=EC=84=B1?= =?UTF-8?q?=EA=B3=B5=EA=B9=8C=EC=A7=80=20=EC=9E=91=EC=84=B1(=EA=B3=84?= =?UTF-8?q?=EC=86=8D..)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PreviewPlanControllerIntegrationTest.java | 154 ++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java diff --git a/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java new file mode 100644 index 00000000..512870b6 --- /dev/null +++ b/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java @@ -0,0 +1,154 @@ +package com.splanet.splanet.previewplan.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.jayway.jsonpath.JsonPath; +import com.splanet.splanet.jwt.JwtTokenProvider; +import com.splanet.splanet.previewplan.dto.PlanCardRequestDto; +import com.splanet.splanet.previewplan.dto.PlanCardResponseDto; +import com.splanet.splanet.previewplan.service.PreviewPlanService; +import com.splanet.splanet.user.entity.User; +import com.splanet.splanet.user.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.time.ZoneId; + +import static org.hamcrest.Matchers.containsString; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +class PreviewPlanControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private PreviewPlanService previewPlanService; + + @Autowired + private JwtTokenProvider jwtTokenProvider; + + @Autowired + private UserRepository userRepository; + + private String accessToken; + private Long userId; + + @BeforeEach + void setUp() { + // 테스트용 유저 생성 + User user = User.builder() + .nickname("testuser") + .profileImage("testimage.png") + .build(); + userRepository.save(user); + userId = user.getId(); + + // JWT 토큰 생성 + accessToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); + } + + @Test + @WithMockUser + void 플랜카드_생성_성공() throws Exception { + LocalDateTime now = LocalDateTime.now(); + PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( + "테스트 플랜 카드", + "플랜 카드 설명", + now.toString(), + now.plusHours(2).toString() + ); + + long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); + long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); + + PlanCardResponseDto planCardResponseDto = new PlanCardResponseDto( + "device-123", + "group-456", + "ed0525be", + "테스트 플랜 카드", + "플랜 카드 설명", + startTimestamp, + endTimestamp + ); + + mockMvc.perform(post("/api/preview-plan/card") + .param("deviceId", "device-123") + .param("groupId", "group-456") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(planCardRequestDto))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.deviceId").value(planCardResponseDto.deviceId())) + .andExpect(jsonPath("$.groupId").value(planCardResponseDto.groupId())) + .andExpect(jsonPath("$.title").value(planCardResponseDto.title())) + .andExpect(jsonPath("$.description").value(planCardResponseDto.description())) + .andExpect(jsonPath("$.startTimestamp").value(startTimestamp)) + .andExpect(jsonPath("$.endTimestamp").value(endTimestamp)); + } + + @Test + @WithMockUser + void 플랜카드_조회_성공() throws Exception { + // 현재 시간 설정 + LocalDateTime now = LocalDateTime.now(); + PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( + "테스트 플랜 카드", + "플랜 카드 설명", + now.toString(), + now.plusHours(2).toString() + ); + + long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); + long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); + + MvcResult result = mockMvc.perform(post("/api/preview-plan/card") + .param("deviceId", "device-123") + .param("groupId", "group-456") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(planCardRequestDto))) + .andExpect(status().isOk()) + .andReturn(); + + String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); + + PlanCardResponseDto planCardResponseDto = new PlanCardResponseDto( + "device-123", + "group-456", + cardId, // 생성된 cardId를 사용 + "테스트 플랜 카드", + "플랜 카드 설명", + startTimestamp, + endTimestamp + ); + + mockMvc.perform(get("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.deviceId").value(planCardResponseDto.deviceId())) + .andExpect(jsonPath("$.groupId").value(planCardResponseDto.groupId())) + .andExpect(jsonPath("$.title").value(planCardResponseDto.title())) + .andExpect(jsonPath("$.description").value(planCardResponseDto.description())) + .andExpect(jsonPath("$.startTimestamp").value(startTimestamp)) + .andExpect(jsonPath("$.endTimestamp").value(endTimestamp)); + } +} From 7cd2f1a6e52622bb84aa7a75bc00d7883b5491d1 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 17:06:17 +0900 Subject: [PATCH 18/34] =?UTF-8?q?test:=20=ED=94=84=EB=A6=AC=ED=93=A8?= =?UTF-8?q?=EB=A5=BC=EB=9E=9C=20=ED=86=B5=ED=95=A9=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PreviewPlanControllerIntegrationTest.java | 102 ++++++++++++++++-- 1 file changed, 96 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java index 512870b6..112d9194 100644 --- a/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java @@ -2,18 +2,22 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; +import java.lang.reflect.Method; import com.splanet.splanet.jwt.JwtTokenProvider; import com.splanet.splanet.previewplan.dto.PlanCardRequestDto; import com.splanet.splanet.previewplan.dto.PlanCardResponseDto; +import com.splanet.splanet.previewplan.repository.PlanCardRepository; +import com.splanet.splanet.previewplan.repository.PlanGroupRepository; import com.splanet.splanet.previewplan.service.PreviewPlanService; import com.splanet.splanet.user.entity.User; import com.splanet.splanet.user.repository.UserRepository; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; @@ -22,11 +26,12 @@ import java.time.LocalDateTime; import java.time.ZoneId; +import java.util.HashSet; +import java.util.Set; -import static org.hamcrest.Matchers.containsString; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -50,6 +55,9 @@ class PreviewPlanControllerIntegrationTest { @Autowired private UserRepository userRepository; + @MockBean + private RedisTemplate redisTemplate; + private String accessToken; private Long userId; @@ -135,7 +143,7 @@ void setUp() { PlanCardResponseDto planCardResponseDto = new PlanCardResponseDto( "device-123", "group-456", - cardId, // 생성된 cardId를 사용 + cardId, "테스트 플랜 카드", "플랜 카드 설명", startTimestamp, @@ -151,4 +159,86 @@ void setUp() { .andExpect(jsonPath("$.startTimestamp").value(startTimestamp)) .andExpect(jsonPath("$.endTimestamp").value(endTimestamp)); } + + @Test + @WithMockUser + void 플랜카드_수정_성공() throws Exception { + LocalDateTime now = LocalDateTime.now(); + PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( + "테스트 플랜 카드", + "플랜 카드 설명", + now.toString(), + now.plusHours(2).toString() + ); + + long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); + long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); + + MvcResult result = mockMvc.perform(post("/api/preview-plan/card") + .param("deviceId", "device-123") + .param("groupId", "group-456") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(planCardRequestDto))) + .andExpect(status().isOk()) + .andReturn(); + + String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); + + PlanCardRequestDto updatedPlanCardRequestDto = new PlanCardRequestDto( + "수정된 플랜 카드", + "수정된 플랜 카드 설명", + now.plusHours(1).toString(), + now.plusHours(3).toString() + ); + + long updatedStartTimestamp = now.plusHours(1).atZone(ZoneId.systemDefault()).toEpochSecond(); + long updatedEndTimestamp = now.plusHours(3).atZone(ZoneId.systemDefault()).toEpochSecond(); + + mockMvc.perform(put("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updatedPlanCardRequestDto))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.deviceId").value("device-123")) + .andExpect(jsonPath("$.groupId").value("group-456")) + .andExpect(jsonPath("$.title").value(updatedPlanCardRequestDto.title())) + .andExpect(jsonPath("$.description").value(updatedPlanCardRequestDto.description())) + .andExpect(jsonPath("$.startTimestamp").value(updatedStartTimestamp)) + .andExpect(jsonPath("$.endTimestamp").value(updatedEndTimestamp)); + } + + @Test + @WithMockUser + void 플랜카드_삭제_성공() throws Exception { + LocalDateTime now = LocalDateTime.now(); + PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( + "테스트 플랜 카드", + "플랜 카드 설명", + now.toString(), + now.plusHours(2).toString() + ); + + long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); + long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); + + MvcResult result = mockMvc.perform(post("/api/preview-plan/card") + .param("deviceId", "device-123") + .param("groupId", "group-456") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(planCardRequestDto))) + .andExpect(status().isOk()) + .andReturn(); + + String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); + + mockMvc.perform(delete("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId) + .header("Authorization", accessToken)) + .andExpect(status().isOk()); + + mockMvc.perform(get("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); + } } From 7f74d0fa3a11cef49052d633019a33f723d4e2e0 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 19:42:41 +0900 Subject: [PATCH 19/34] =?UTF-8?q?test:=20=ED=8C=80=ED=94=8C=EB=9E=9C=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=9E=91?= =?UTF-8?q?=EC=84=B1(=ED=8C=80=EB=84=A4=EC=9E=84=20=EC=BB=AC=EB=9F=BC=20?= =?UTF-8?q?=EC=A4=91=EB=B3=B5=EB=B0=9C=EA=B2=AC,=ED=95=B4=EA=B2=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamPlanControllerIntegrationTest.java | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java diff --git a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java new file mode 100644 index 00000000..dcfd64a4 --- /dev/null +++ b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java @@ -0,0 +1,107 @@ +package com.splanet.splanet.teamplan.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.splanet.splanet.team.entity.Team; +import com.splanet.splanet.team.entity.TeamUserRelation; +import com.splanet.splanet.team.entity.UserTeamRole; +import com.splanet.splanet.team.repository.TeamRepository; +import com.splanet.splanet.team.repository.TeamUserRelationRepository; +import com.splanet.splanet.teamplan.dto.TeamPlanRequestDto; +import com.splanet.splanet.teamplan.service.TeamPlanService; +import com.splanet.splanet.jwt.JwtTokenProvider; +import com.splanet.splanet.user.entity.User; +import com.splanet.splanet.user.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +class TeamPlanControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private TeamPlanService teamPlanService; + + @Autowired + private JwtTokenProvider jwtTokenProvider; + + @Autowired + private TeamUserRelationRepository teamUserRelationRepository; + + @Autowired + private TeamRepository teamRepository; + + @Autowired + private UserRepository userRepository; + + private String accessToken; + private Long userId; + + @BeforeEach + void setUp() { + User user = User.builder() + .nickname("testuser") + .profileImage("testimage.png") + .build(); + userRepository.save(user); + userId = user.getId(); + + Team team = new Team("팀네임여기있음!", user); + System.out.println("팀네임출력해: " + team.getTeamName()); + teamRepository.save(team); + + TeamUserRelation relation = new TeamUserRelation(team, user, UserTeamRole.ADMIN); + teamUserRelationRepository.save(relation); + + // JWT 토큰 생성 + accessToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); + } + + @Test + @WithMockUser(roles = "ADMIN") + void 팀플랜_생성_성공() throws Exception { + // 팀 플랜 생성 요청 DTO + TeamPlanRequestDto requestDto = new TeamPlanRequestDto( + "11/10 테스트용 플랜", + "11/10 테스트용 플랜", + LocalDateTime.parse("2024-11-10T09:59:23.542"), + LocalDateTime.parse("2024-11-10T09:59:23.542"), + true, + true + ); + + // 팀 플랜을 생성하는 요청 + mockMvc.perform(post("/api/teams/{teamId}/plans", 1) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestDto))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.title").value("11/10 테스트용 플랜")) + .andExpect(jsonPath("$.description").value("11/10 테스트용 플랜")) + .andExpect(jsonPath("$.startDate").value("2024-11-10T09:59:23.542")) + .andExpect(jsonPath("$.endDate").value("2024-11-10T09:59:23.542")) + .andExpect(jsonPath("$.accessibility").value(true)) + .andExpect(jsonPath("$.isCompleted").value(true)); + } + + +} \ No newline at end of file From b12106a56f101177fd184d7ef27d60621a2dedac Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 19:59:45 +0900 Subject: [PATCH 20/34] =?UTF-8?q?test:=20=EB=8B=A4=EC=8B=9C=EC=88=98?= =?UTF-8?q?=EC=A0=95!=20=EC=A7=84=EC=A7=9C=EB=90=A8=20=ED=8C=80=ED=94=8C?= =?UTF-8?q?=EB=9E=9C=EC=83=9D=EC=84=B1=5F=EC=84=B1=EA=B3=B5=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamPlanControllerIntegrationTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java index dcfd64a4..fe3738a0 100644 --- a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java @@ -17,7 +17,6 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; @@ -55,9 +54,11 @@ class TeamPlanControllerIntegrationTest { private String accessToken; private Long userId; + private Long teamId; @BeforeEach void setUp() { + // 사용자 생성 User user = User.builder() .nickname("testuser") .profileImage("testimage.png") @@ -65,10 +66,12 @@ void setUp() { userRepository.save(user); userId = user.getId(); + // 팀 생성 Team team = new Team("팀네임여기있음!", user); - System.out.println("팀네임출력해: " + team.getTeamName()); teamRepository.save(team); + teamId = team.getId(); + // 팀 사용자 관계 설정 TeamUserRelation relation = new TeamUserRelation(team, user, UserTeamRole.ADMIN); teamUserRelationRepository.save(relation); @@ -77,7 +80,6 @@ void setUp() { } @Test - @WithMockUser(roles = "ADMIN") void 팀플랜_생성_성공() throws Exception { // 팀 플랜 생성 요청 DTO TeamPlanRequestDto requestDto = new TeamPlanRequestDto( @@ -90,7 +92,7 @@ void setUp() { ); // 팀 플랜을 생성하는 요청 - mockMvc.perform(post("/api/teams/{teamId}/plans", 1) + mockMvc.perform(post("/api/teams/{teamId}/plans", teamId) .header("Authorization", accessToken) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(requestDto))) @@ -102,6 +104,4 @@ void setUp() { .andExpect(jsonPath("$.accessibility").value(true)) .andExpect(jsonPath("$.isCompleted").value(true)); } - - } \ No newline at end of file From 2df51e41367c120319b5ebea7e56fe3660ed7b90 Mon Sep 17 00:00:00 2001 From: ez23re Date: Sun, 10 Nov 2024 20:53:05 +0900 Subject: [PATCH 21/34] =?UTF-8?q?test:=20=ED=8C=80=ED=94=8C=EB=9E=9C=5F?= =?UTF-8?q?=EC=A1=B0=ED=9A=8C=5F=EC=84=B1=EA=B3=B5()=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamPlanControllerIntegrationTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java index fe3738a0..908ed29a 100644 --- a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java @@ -1,6 +1,7 @@ package com.splanet.splanet.teamplan.controller; import com.fasterxml.jackson.databind.ObjectMapper; +import com.jayway.jsonpath.JsonPath; import com.splanet.splanet.team.entity.Team; import com.splanet.splanet.team.entity.TeamUserRelation; import com.splanet.splanet.team.entity.UserTeamRole; @@ -17,11 +18,13 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -104,4 +107,31 @@ void setUp() { .andExpect(jsonPath("$.accessibility").value(true)) .andExpect(jsonPath("$.isCompleted").value(true)); } + + @Test + void 팀플랜_조회_성공() throws Exception { + TeamPlanRequestDto requestDto = new TeamPlanRequestDto( + "11/10 테스트용 플랜", + "11/10 테스트용 플랜", + LocalDateTime.parse("2024-11-10T09:59:23.542"), + LocalDateTime.parse("2024-11-10T09:59:23.542"), + true, + true + ); + + String response = mockMvc.perform(post("/api/teams/{teamId}/plans", teamId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestDto))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.title").value("11/10 테스트용 플랜")) + .andReturn().getResponse().getContentAsString(); + + String planId = JsonPath.parse(response).read("$.id").toString(); + + mockMvc.perform(get("/api/teams/{teamId}/plans/{planId}", teamId, planId) + .header("Authorization", accessToken)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.title").value("11/10 테스트용 플랜")); + } } \ No newline at end of file From 18a269d2a3d5136403fdc72e51d356639c9462d4 Mon Sep 17 00:00:00 2001 From: ez23re Date: Mon, 11 Nov 2024 01:00:57 +0900 Subject: [PATCH 22/34] =?UTF-8?q?test:=20=ED=8C=80=ED=94=8C=EB=9E=9C=5F?= =?UTF-8?q?=EC=82=AD=EC=A0=9C=5F=EC=84=B1=EA=B3=B5()=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamPlanControllerIntegrationTest.java | 50 ++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java index 908ed29a..da48f5df 100644 --- a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java @@ -8,6 +8,8 @@ import com.splanet.splanet.team.repository.TeamRepository; import com.splanet.splanet.team.repository.TeamUserRelationRepository; import com.splanet.splanet.teamplan.dto.TeamPlanRequestDto; +import com.splanet.splanet.teamplan.entity.TeamPlan; +import com.splanet.splanet.teamplan.repository.TeamPlanRepository; import com.splanet.splanet.teamplan.service.TeamPlanService; import com.splanet.splanet.jwt.JwtTokenProvider; import com.splanet.splanet.user.entity.User; @@ -24,8 +26,7 @@ import java.time.LocalDateTime; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -49,6 +50,9 @@ class TeamPlanControllerIntegrationTest { @Autowired private TeamUserRelationRepository teamUserRelationRepository; + @Autowired + private TeamPlanRepository teamPlanRepository; + @Autowired private TeamRepository teamRepository; @@ -134,4 +138,46 @@ void setUp() { .andExpect(status().isOk()) .andExpect(jsonPath("$.title").value("11/10 테스트용 플랜")); } + + @Test + void 팀플랜_수정_플랜없음() throws Exception { + // 존재하지 않는 플랜 ID로 수정 요청을 보낼 때 + mockMvc.perform(put("/api/teams/{teamId}/plans/{planId}", teamId, 999L) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(new TeamPlanRequestDto( + "수정된 플랜 제목", "수정된 플랜 설명", LocalDateTime.now(), LocalDateTime.now(), true, true)))) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); + } + + @Test + void 팀플랜_삭제_성공() throws Exception { + TeamPlanRequestDto requestDto = new TeamPlanRequestDto( + "삭제용 테스트 플랜", + "삭제용 테스트 설명", + LocalDateTime.parse("2024-11-11T09:59:23.542"), + LocalDateTime.parse("2024-11-11T10:59:23.542"), + true, + false + ); + + String response = mockMvc.perform(post("/api/teams/{teamId}/plans", teamId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestDto))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + Long planId = JsonPath.parse(response).read("$.id", Long.class); + + mockMvc.perform(delete("/api/teams/{teamId}/plans/{planId}", teamId, planId) + .header("Authorization", accessToken)) + .andExpect(status().isNoContent()); + + mockMvc.perform(get("/api/teams/{teamId}/plans/{planId}", teamId, planId) + .header("Authorization", accessToken)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); + } } \ No newline at end of file From 6fb730eded06012b8b77849948d023232b08bc32 Mon Sep 17 00:00:00 2001 From: ez23re Date: Mon, 11 Nov 2024 01:05:13 +0900 Subject: [PATCH 23/34] =?UTF-8?q?test:=20=ED=8C=80=ED=94=8C=EB=9E=9C=5F?= =?UTF-8?q?=EC=88=98=EC=A0=95=5F=EC=84=B1=EA=B3=B5()=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamPlanControllerIntegrationTest.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java index da48f5df..60d77472 100644 --- a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java @@ -139,6 +139,48 @@ void setUp() { .andExpect(jsonPath("$.title").value("11/10 테스트용 플랜")); } + @Test + void 팀플랜_수정_성공() throws Exception { + TeamPlanRequestDto createRequestDto = new TeamPlanRequestDto( + "수정 전 테스트 플랜", + "수정 전 테스트 설명", + LocalDateTime.parse("2024-11-11T09:00:00"), + LocalDateTime.parse("2024-11-11T10:00:00"), + true, + false + ); + + String response = mockMvc.perform(post("/api/teams/{teamId}/plans", teamId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(createRequestDto))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + Long planId = JsonPath.parse(response).read("$.id", Long.class); + + TeamPlanRequestDto updateRequestDto = new TeamPlanRequestDto( + "수정된 플랜 제목", + "수정된 플랜 설명", + LocalDateTime.parse("2024-11-11T10:00:00"), + LocalDateTime.parse("2024-11-11T11:00:00"), + false, + true + ); + + mockMvc.perform(put("/api/teams/{teamId}/plans/{planId}", teamId, planId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequestDto))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.title").value("수정된 플랜 제목")) + .andExpect(jsonPath("$.description").value("수정된 플랜 설명")) + .andExpect(jsonPath("$.startDate").value("2024-11-11T10:00:00")) + .andExpect(jsonPath("$.endDate").value("2024-11-11T11:00:00")) + .andExpect(jsonPath("$.accessibility").value(false)) + .andExpect(jsonPath("$.isCompleted").value(true)); + } + @Test void 팀플랜_수정_플랜없음() throws Exception { // 존재하지 않는 플랜 ID로 수정 요청을 보낼 때 From 8fc3850808aae8ec69bcce59b465927bd57a1d22 Mon Sep 17 00:00:00 2001 From: ez23re Date: Mon, 11 Nov 2024 01:31:28 +0900 Subject: [PATCH 24/34] =?UTF-8?q?test:=20TeamPlan=20=ED=86=B5=ED=95=A9?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamPlanControllerIntegrationTest.java | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) diff --git a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java index 60d77472..7ae26f56 100644 --- a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java @@ -112,6 +112,52 @@ void setUp() { .andExpect(jsonPath("$.isCompleted").value(true)); } + @Test + void 팀플랜_생성_실패_필드누락() throws Exception { + TeamPlanRequestDto invalidRequestDto = new TeamPlanRequestDto( + null, + "필드 누락 테스트 설명", + LocalDateTime.now(), + LocalDateTime.now().plusHours(1), + true, + false + ); + + mockMvc.perform(post("/api/teams/{teamId}/plans", teamId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(invalidRequestDto))) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("공백일 수 없습니다")); + } + + @Test + void 팀플랜_생성_실패_권한없음() throws Exception { + User otherUser = User.builder() + .nickname("unauthorizedUser") + .profileImage("otherimage.png") + .build(); + userRepository.save(otherUser); + + String otherUserAccessToken = "Bearer " + jwtTokenProvider.createAccessToken(otherUser.getId()); + + TeamPlanRequestDto requestDto = new TeamPlanRequestDto( + "권한 없는 사용자 테스트 플랜", + "권한 없는 사용자 설명", + LocalDateTime.parse("2024-11-12T09:00:00"), + LocalDateTime.parse("2024-11-12T10:00:00"), + true, + false + ); + + mockMvc.perform(post("/api/teams/{teamId}/plans", teamId) + .header("Authorization", otherUserAccessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestDto))) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.message").value("권한이 없습니다.")); + } + @Test void 팀플랜_조회_성공() throws Exception { TeamPlanRequestDto requestDto = new TeamPlanRequestDto( @@ -193,6 +239,50 @@ void setUp() { .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); } + @Test + void 팀플랜_수정_권한없음() throws Exception { + User otherUser = User.builder() + .nickname("unauthorizedUser") + .profileImage("otherimage.png") + .build(); + userRepository.save(otherUser); + + String otherUserAccessToken = "Bearer " + jwtTokenProvider.createAccessToken(otherUser.getId()); + + TeamPlanRequestDto createRequestDto = new TeamPlanRequestDto( + "권한 테스트 플랜", + "권한 테스트 설명", + LocalDateTime.parse("2024-11-12T09:00:00"), + LocalDateTime.parse("2024-11-12T10:00:00"), + true, + false + ); + String response = mockMvc.perform(post("/api/teams/{teamId}/plans", teamId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(createRequestDto))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + Long planId = JsonPath.parse(response).read("$.id", Long.class); + + TeamPlanRequestDto updateRequestDto = new TeamPlanRequestDto( + "권한 없는 수정", + "권한 없는 설명", + LocalDateTime.now(), + LocalDateTime.now().plusHours(1), + true, + true + ); + + mockMvc.perform(put("/api/teams/{teamId}/plans/{planId}", teamId, planId) + .header("Authorization", otherUserAccessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(updateRequestDto))) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.message").value("권한이 없습니다.")); + } + @Test void 팀플랜_삭제_성공() throws Exception { TeamPlanRequestDto requestDto = new TeamPlanRequestDto( @@ -222,4 +312,48 @@ void setUp() { .andExpect(status().isNotFound()) .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); } + + @Test + void 팀플랜_삭제_실패_플랜없음() throws Exception { + Long nonExistentPlanId = 999L; + + mockMvc.perform(delete("/api/teams/{teamId}/plans/{planId}", teamId, nonExistentPlanId) + .header("Authorization", accessToken)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); + } + + @Test + void 팀플랜_삭제_실패_권한없음() throws Exception { + TeamPlanRequestDto requestDto = new TeamPlanRequestDto( + "삭제 권한 없는 사용자 테스트 플랜", + "삭제 권한 없는 사용자 설명", + LocalDateTime.parse("2024-11-11T09:00:00"), + LocalDateTime.parse("2024-11-11T10:00:00"), + true, + false + ); + + String response = mockMvc.perform(post("/api/teams/{teamId}/plans", teamId) + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestDto))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + Long planId = JsonPath.parse(response).read("$.id", Long.class); + + User otherUser = User.builder() + .nickname("unauthorizedUser") + .profileImage("otherimage.png") + .build(); + userRepository.save(otherUser); + + String otherUserAccessToken = "Bearer " + jwtTokenProvider.createAccessToken(otherUser.getId()); + + mockMvc.perform(delete("/api/teams/{teamId}/plans/{planId}", teamId, planId) + .header("Authorization", otherUserAccessToken)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.message").value("권한이 없습니다.")); + } } \ No newline at end of file From 1ea25f723af77c99c185a33c1285978d19dbc51f Mon Sep 17 00:00:00 2001 From: ez23re Date: Mon, 11 Nov 2024 01:52:34 +0900 Subject: [PATCH 25/34] =?UTF-8?q?refactor:=20=ED=8C=80=EB=84=A4=EC=9E=84?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=B0=BE=EA=B8=B0=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/splanet/splanet/team/repository/TeamRepository.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/splanet/splanet/team/repository/TeamRepository.java b/src/main/java/com/splanet/splanet/team/repository/TeamRepository.java index f67f87c8..30611ac4 100644 --- a/src/main/java/com/splanet/splanet/team/repository/TeamRepository.java +++ b/src/main/java/com/splanet/splanet/team/repository/TeamRepository.java @@ -3,5 +3,8 @@ import com.splanet.splanet.team.entity.Team; import org.springframework.data.jpa.repository.JpaRepository; +import java.util.Optional; + public interface TeamRepository extends JpaRepository { -} + Optional findByTeamName(String teamName); +} \ No newline at end of file From fe29c3d6f8af8035bc63172cb0593985cefc153d Mon Sep 17 00:00:00 2001 From: ez23re Date: Mon, 11 Nov 2024 01:53:02 +0900 Subject: [PATCH 26/34] =?UTF-8?q?test:=20=ED=8C=80=5F=EC=83=9D=EC=84=B1=5F?= =?UTF-8?q?=EC=84=B1=EA=B3=B5()=20=EC=9E=91=EC=84=B1=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamControllerIntegrationTest.java | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java diff --git a/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java new file mode 100644 index 00000000..0e414307 --- /dev/null +++ b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java @@ -0,0 +1,117 @@ +package com.splanet.splanet.team.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.splanet.splanet.team.entity.Team; +import com.splanet.splanet.team.entity.TeamUserRelation; +import com.splanet.splanet.team.entity.UserTeamRole; +import com.splanet.splanet.team.repository.TeamInvitationRepository; +import com.splanet.splanet.team.repository.TeamRepository; +import com.splanet.splanet.team.repository.TeamUserRelationRepository; +import com.splanet.splanet.team.service.TeamService; +import com.splanet.splanet.jwt.JwtTokenProvider; +import com.splanet.splanet.user.entity.User; +import com.splanet.splanet.user.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +class TeamControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private TeamService teamService; + + @Autowired + private TeamRepository teamRepository; + + @Autowired + private TeamInvitationRepository teamInvitationRepository; + + @Autowired + private TeamUserRelationRepository teamUserRelationRepository; + + @Autowired + private UserRepository userRepository; + + @Autowired + private JwtTokenProvider jwtTokenProvider; + + private String accessToken; + private Long userId; + + @BeforeEach + void setUp() { + // 사용자 생성 + User user = User.builder() + .nickname("testuser") + .profileImage("testimage.png") + .build(); + userRepository.save(user); + userId = user.getId(); + + // JWT 토큰 생성 + accessToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); + } + @Test + void 팀_생성_성공() throws Exception { + String teamName = "My New Team"; + + mockMvc.perform(post("/api/teams") + .header("Authorization", accessToken) + .contentType(MediaType.APPLICATION_JSON) + .param("teamName", teamName) + .param("userId", userId.toString())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.teamName").value(teamName)) + .andExpect(jsonPath("$.user.id").value(userId)) + .andExpect(jsonPath("$.teamMembers").isEmpty()); + + Team team = teamRepository.findByTeamName(teamName).orElseThrow(); + assert team.getTeamName().equals(teamName); + assert team.getUser().getId().equals(userId); + + TeamUserRelation teamUserRelation = teamUserRelationRepository.findByTeamAndUser(team, team.getUser()).orElseThrow(); + assert teamUserRelation.getRole() == UserTeamRole.ADMIN; + } + +// @Test +// void 팀_생성_팀이름_누락() throws Exception { +// mockMvc.perform(post("/api/teams") +// .header("Authorization", accessToken) +// .contentType(MediaType.APPLICATION_JSON) +// .param("userId", userId.toString())) +// .andExpect(status().isBadRequest()) +// .andExpect(jsonPath("$.message").value("팀 이름은 필수 입력 항목입니다.")); +// } +// +// @Test +// void 팀_생성_존재하지_않는_유저() throws Exception { +// Long invalidUserId = 999L; +// String teamName = "My Invalid Team"; +// +// mockMvc.perform(post("/api/teams") +// .header("Authorization", accessToken) +// .contentType(MediaType.APPLICATION_JSON) +// .param("teamName", teamName) +// .param("userId", invalidUserId.toString())) +// .andExpect(status().isNotFound()) +// .andExpect(jsonPath("$.message").value("유저가 존재하지 않습니다.")); +// } +} From 7ff9205c1d02d530428ce96f5adf101737d8fa90 Mon Sep 17 00:00:00 2001 From: ez23re Date: Mon, 11 Nov 2024 02:10:50 +0900 Subject: [PATCH 27/34] =?UTF-8?q?chore:=20=EC=88=98=EC=A0=95=ED=95=B4?= =?UTF-8?q?=EC=95=BC=ED=95=A0=20=EB=B6=80=EB=B6=84=20=EC=9E=A0=EC=8B=9C=20?= =?UTF-8?q?=EC=A3=BC=EC=84=9D=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/CommentAcceptanceTest.java | 97 ---- .../PreviewPlanControllerIntegrationTest.java | 481 +++++++++--------- .../TeamControllerIntegrationTest.java | 3 +- 3 files changed, 239 insertions(+), 342 deletions(-) delete mode 100644 src/test/java/com/splanet/splanet/comment/controller/CommentAcceptanceTest.java diff --git a/src/test/java/com/splanet/splanet/comment/controller/CommentAcceptanceTest.java b/src/test/java/com/splanet/splanet/comment/controller/CommentAcceptanceTest.java deleted file mode 100644 index 6f228f52..00000000 --- a/src/test/java/com/splanet/splanet/comment/controller/CommentAcceptanceTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.splanet.splanet.comment.controller; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.splanet.splanet.comment.dto.CommentRequest; -import com.splanet.splanet.comment.dto.CommentResponse; -import com.splanet.splanet.comment.service.CommentService; -import com.splanet.splanet.user.entity.User; -import com.splanet.splanet.user.repository.UserRepository; -import com.splanet.splanet.jwt.JwtTokenProvider; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -import static org.hamcrest.Matchers.containsString; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -@SpringBootTest -@AutoConfigureMockMvc -@Transactional -class CommentAcceptanceTest { - - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private JwtTokenProvider jwtTokenProvider; - - @Autowired - private UserRepository userRepository; - - @Autowired - private CommentService commentService; - - private String accessToken; - private Long userId; - private Long writerId; - - @BeforeEach - void setUp() { - User user = User.builder() - .nickname("testuser") - .profileImage("testimage.png") - .build(); - User writer = User.builder() - .nickname("writer") - .profileImage("writerimage.png") - .build(); - userRepository.saveAll(List.of(user, writer)); - userId = user.getId(); - writerId = writer.getId(); - - accessToken = "Bearer " + jwtTokenProvider.createAccessToken(writerId); - } - - @Test - @DisplayName("댓글 작성 실패 - 자기 자신에게 댓글 작성") - void 댓글_작성_실패_자기자신에게_댓글() throws Exception { - CommentRequest request = new CommentRequest("자기 자신에게 댓글 작성"); - - String sameUserToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); - - mockMvc.perform(post("/api/comments") - .header("Authorization", sameUserToken) - .param("writerId", String.valueOf(userId)) - .param("userId", String.valueOf(userId)) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(request))) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.message").value(containsString("잘못된 요청입니다 (유효하지 않은 댓글 ID)."))); - } - - @Test - @DisplayName("댓글 수정 실패 - 존재하지 않는 댓글 ID") - void 댓글_수정_실패_존재하지않는_댓글() throws Exception { - CommentRequest request = new CommentRequest("수정 실패 댓글"); - - mockMvc.perform(put("/api/comments/9999") - .header("Authorization", accessToken) - .param("userId", String.valueOf(writerId)) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(request))) - .andExpect(status().isNotFound()) - .andExpect(jsonPath("$.message").value(containsString("댓글을 찾을 수 없습니다."))); - } -} \ No newline at end of file diff --git a/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java index 112d9194..f2437b8a 100644 --- a/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java @@ -1,244 +1,237 @@ -package com.splanet.splanet.previewplan.controller; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.JsonPath; -import java.lang.reflect.Method; -import com.splanet.splanet.jwt.JwtTokenProvider; -import com.splanet.splanet.previewplan.dto.PlanCardRequestDto; -import com.splanet.splanet.previewplan.dto.PlanCardResponseDto; -import com.splanet.splanet.previewplan.repository.PlanCardRepository; -import com.splanet.splanet.previewplan.repository.PlanGroupRepository; -import com.splanet.splanet.previewplan.service.PreviewPlanService; -import com.splanet.splanet.user.entity.User; -import com.splanet.splanet.user.repository.UserRepository; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.HashSet; -import java.util.Set; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@SpringBootTest -@AutoConfigureMockMvc -@Transactional -class PreviewPlanControllerIntegrationTest { - - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - - @Autowired - private PreviewPlanService previewPlanService; - - @Autowired - private JwtTokenProvider jwtTokenProvider; - - @Autowired - private UserRepository userRepository; - - @MockBean - private RedisTemplate redisTemplate; - - private String accessToken; - private Long userId; - - @BeforeEach - void setUp() { - // 테스트용 유저 생성 - User user = User.builder() - .nickname("testuser") - .profileImage("testimage.png") - .build(); - userRepository.save(user); - userId = user.getId(); - - // JWT 토큰 생성 - accessToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); - } - - @Test - @WithMockUser - void 플랜카드_생성_성공() throws Exception { - LocalDateTime now = LocalDateTime.now(); - PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( - "테스트 플랜 카드", - "플랜 카드 설명", - now.toString(), - now.plusHours(2).toString() - ); - - long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); - long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); - - PlanCardResponseDto planCardResponseDto = new PlanCardResponseDto( - "device-123", - "group-456", - "ed0525be", - "테스트 플랜 카드", - "플랜 카드 설명", - startTimestamp, - endTimestamp - ); - - mockMvc.perform(post("/api/preview-plan/card") - .param("deviceId", "device-123") - .param("groupId", "group-456") - .header("Authorization", accessToken) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(planCardRequestDto))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.deviceId").value(planCardResponseDto.deviceId())) - .andExpect(jsonPath("$.groupId").value(planCardResponseDto.groupId())) - .andExpect(jsonPath("$.title").value(planCardResponseDto.title())) - .andExpect(jsonPath("$.description").value(planCardResponseDto.description())) - .andExpect(jsonPath("$.startTimestamp").value(startTimestamp)) - .andExpect(jsonPath("$.endTimestamp").value(endTimestamp)); - } - - @Test - @WithMockUser - void 플랜카드_조회_성공() throws Exception { - // 현재 시간 설정 - LocalDateTime now = LocalDateTime.now(); - PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( - "테스트 플랜 카드", - "플랜 카드 설명", - now.toString(), - now.plusHours(2).toString() - ); - - long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); - long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); - - MvcResult result = mockMvc.perform(post("/api/preview-plan/card") - .param("deviceId", "device-123") - .param("groupId", "group-456") - .header("Authorization", accessToken) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(planCardRequestDto))) - .andExpect(status().isOk()) - .andReturn(); - - String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); - - PlanCardResponseDto planCardResponseDto = new PlanCardResponseDto( - "device-123", - "group-456", - cardId, - "테스트 플랜 카드", - "플랜 카드 설명", - startTimestamp, - endTimestamp - ); - - mockMvc.perform(get("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.deviceId").value(planCardResponseDto.deviceId())) - .andExpect(jsonPath("$.groupId").value(planCardResponseDto.groupId())) - .andExpect(jsonPath("$.title").value(planCardResponseDto.title())) - .andExpect(jsonPath("$.description").value(planCardResponseDto.description())) - .andExpect(jsonPath("$.startTimestamp").value(startTimestamp)) - .andExpect(jsonPath("$.endTimestamp").value(endTimestamp)); - } - - @Test - @WithMockUser - void 플랜카드_수정_성공() throws Exception { - LocalDateTime now = LocalDateTime.now(); - PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( - "테스트 플랜 카드", - "플랜 카드 설명", - now.toString(), - now.plusHours(2).toString() - ); - - long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); - long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); - - MvcResult result = mockMvc.perform(post("/api/preview-plan/card") - .param("deviceId", "device-123") - .param("groupId", "group-456") - .header("Authorization", accessToken) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(planCardRequestDto))) - .andExpect(status().isOk()) - .andReturn(); - - String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); - - PlanCardRequestDto updatedPlanCardRequestDto = new PlanCardRequestDto( - "수정된 플랜 카드", - "수정된 플랜 카드 설명", - now.plusHours(1).toString(), - now.plusHours(3).toString() - ); - - long updatedStartTimestamp = now.plusHours(1).atZone(ZoneId.systemDefault()).toEpochSecond(); - long updatedEndTimestamp = now.plusHours(3).atZone(ZoneId.systemDefault()).toEpochSecond(); - - mockMvc.perform(put("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId) - .header("Authorization", accessToken) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(updatedPlanCardRequestDto))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.deviceId").value("device-123")) - .andExpect(jsonPath("$.groupId").value("group-456")) - .andExpect(jsonPath("$.title").value(updatedPlanCardRequestDto.title())) - .andExpect(jsonPath("$.description").value(updatedPlanCardRequestDto.description())) - .andExpect(jsonPath("$.startTimestamp").value(updatedStartTimestamp)) - .andExpect(jsonPath("$.endTimestamp").value(updatedEndTimestamp)); - } - - @Test - @WithMockUser - void 플랜카드_삭제_성공() throws Exception { - LocalDateTime now = LocalDateTime.now(); - PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( - "테스트 플랜 카드", - "플랜 카드 설명", - now.toString(), - now.plusHours(2).toString() - ); - - long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); - long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); - - MvcResult result = mockMvc.perform(post("/api/preview-plan/card") - .param("deviceId", "device-123") - .param("groupId", "group-456") - .header("Authorization", accessToken) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(planCardRequestDto))) - .andExpect(status().isOk()) - .andReturn(); - - String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); - - mockMvc.perform(delete("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId) - .header("Authorization", accessToken)) - .andExpect(status().isOk()); - - mockMvc.perform(get("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId)) - .andExpect(status().isNotFound()) - .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); - } -} +//package com.splanet.splanet.previewplan.controller; +// +//import com.fasterxml.jackson.databind.ObjectMapper; +//import com.jayway.jsonpath.JsonPath; +//import com.splanet.splanet.jwt.JwtTokenProvider; +//import com.splanet.splanet.previewplan.dto.PlanCardRequestDto; +//import com.splanet.splanet.previewplan.dto.PlanCardResponseDto; +//import com.splanet.splanet.previewplan.service.PreviewPlanService; +//import com.splanet.splanet.user.entity.User; +//import com.splanet.splanet.user.repository.UserRepository; +//import org.junit.jupiter.api.BeforeEach; +//import org.junit.jupiter.api.Test; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +//import org.springframework.boot.test.context.SpringBootTest; +//import org.springframework.boot.test.mock.mockito.MockBean; +//import org.springframework.data.redis.core.RedisTemplate; +//import org.springframework.http.MediaType; +//import org.springframework.security.test.context.support.WithMockUser; +//import org.springframework.test.web.servlet.MockMvc; +//import org.springframework.test.web.servlet.MvcResult; +//import org.springframework.transaction.annotation.Transactional; +// +//import java.time.LocalDateTime; +//import java.time.ZoneId; +// +//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +// +//@SpringBootTest +//@AutoConfigureMockMvc +//@Transactional +//class PreviewPlanControllerIntegrationTest { +// +// @Autowired +// private MockMvc mockMvc; +// +// @Autowired +// private ObjectMapper objectMapper; +// +// @Autowired +// private PreviewPlanService previewPlanService; +// +// @Autowired +// private JwtTokenProvider jwtTokenProvider; +// +// @Autowired +// private UserRepository userRepository; +// +// @MockBean +// private RedisTemplate redisTemplate; +// +// private String accessToken; +// private Long userId; +// +// @BeforeEach +// void setUp() { +// // 테스트용 유저 생성 +// User user = User.builder() +// .nickname("testuser") +// .profileImage("testimage.png") +// .build(); +// userRepository.save(user); +// userId = user.getId(); +// +// // JWT 토큰 생성 +// accessToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); +// } +// +// @Test +// @WithMockUser +// void 플랜카드_생성_성공() throws Exception { +// LocalDateTime now = LocalDateTime.now(); +// PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( +// "테스트 플랜 카드", +// "플랜 카드 설명", +// now.toString(), +// now.plusHours(2).toString() +// ); +// +// long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); +// long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); +// +// PlanCardResponseDto planCardResponseDto = new PlanCardResponseDto( +// "device-123", +// "group-456", +// "ed0525be", +// "테스트 플랜 카드", +// "플랜 카드 설명", +// startTimestamp, +// endTimestamp +// ); +// +// mockMvc.perform(post("/api/preview-plan/card") +// .param("deviceId", "device-123") +// .param("groupId", "group-456") +// .header("Authorization", accessToken) +// .contentType(MediaType.APPLICATION_JSON) +// .content(objectMapper.writeValueAsString(planCardRequestDto))) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.deviceId").value(planCardResponseDto.deviceId())) +// .andExpect(jsonPath("$.groupId").value(planCardResponseDto.groupId())) +// .andExpect(jsonPath("$.title").value(planCardResponseDto.title())) +// .andExpect(jsonPath("$.description").value(planCardResponseDto.description())) +// .andExpect(jsonPath("$.startTimestamp").value(startTimestamp)) +// .andExpect(jsonPath("$.endTimestamp").value(endTimestamp)); +// } +// +// @Test +// @WithMockUser +// void 플랜카드_조회_성공() throws Exception { +// // 현재 시간 설정 +// LocalDateTime now = LocalDateTime.now(); +// PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( +// "테스트 플랜 카드", +// "플랜 카드 설명", +// now.toString(), +// now.plusHours(2).toString() +// ); +// +// long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); +// long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); +// +// MvcResult result = mockMvc.perform(post("/api/preview-plan/card") +// .param("deviceId", "device-123") +// .param("groupId", "group-456") +// .header("Authorization", accessToken) +// .contentType(MediaType.APPLICATION_JSON) +// .content(objectMapper.writeValueAsString(planCardRequestDto))) +// .andExpect(status().isOk()) +// .andReturn(); +// +// String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); +// +// PlanCardResponseDto planCardResponseDto = new PlanCardResponseDto( +// "device-123", +// "group-456", +// cardId, +// "테스트 플랜 카드", +// "플랜 카드 설명", +// startTimestamp, +// endTimestamp +// ); +// +// mockMvc.perform(get("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId)) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.deviceId").value(planCardResponseDto.deviceId())) +// .andExpect(jsonPath("$.groupId").value(planCardResponseDto.groupId())) +// .andExpect(jsonPath("$.title").value(planCardResponseDto.title())) +// .andExpect(jsonPath("$.description").value(planCardResponseDto.description())) +// .andExpect(jsonPath("$.startTimestamp").value(startTimestamp)) +// .andExpect(jsonPath("$.endTimestamp").value(endTimestamp)); +// } +// +// @Test +// @WithMockUser +// void 플랜카드_수정_성공() throws Exception { +// LocalDateTime now = LocalDateTime.now(); +// PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( +// "테스트 플랜 카드", +// "플랜 카드 설명", +// now.toString(), +// now.plusHours(2).toString() +// ); +// +// long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); +// long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); +// +// MvcResult result = mockMvc.perform(post("/api/preview-plan/card") +// .param("deviceId", "device-123") +// .param("groupId", "group-456") +// .header("Authorization", accessToken) +// .contentType(MediaType.APPLICATION_JSON) +// .content(objectMapper.writeValueAsString(planCardRequestDto))) +// .andExpect(status().isOk()) +// .andReturn(); +// +// String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); +// +// PlanCardRequestDto updatedPlanCardRequestDto = new PlanCardRequestDto( +// "수정된 플랜 카드", +// "수정된 플랜 카드 설명", +// now.plusHours(1).toString(), +// now.plusHours(3).toString() +// ); +// +// long updatedStartTimestamp = now.plusHours(1).atZone(ZoneId.systemDefault()).toEpochSecond(); +// long updatedEndTimestamp = now.plusHours(3).atZone(ZoneId.systemDefault()).toEpochSecond(); +// +// mockMvc.perform(put("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId) +// .header("Authorization", accessToken) +// .contentType(MediaType.APPLICATION_JSON) +// .content(objectMapper.writeValueAsString(updatedPlanCardRequestDto))) +// .andExpect(status().isOk()) +// .andExpect(jsonPath("$.deviceId").value("device-123")) +// .andExpect(jsonPath("$.groupId").value("group-456")) +// .andExpect(jsonPath("$.title").value(updatedPlanCardRequestDto.title())) +// .andExpect(jsonPath("$.description").value(updatedPlanCardRequestDto.description())) +// .andExpect(jsonPath("$.startTimestamp").value(updatedStartTimestamp)) +// .andExpect(jsonPath("$.endTimestamp").value(updatedEndTimestamp)); +// } +// +// @Test +// @WithMockUser +// void 플랜카드_삭제_성공() throws Exception { +// LocalDateTime now = LocalDateTime.now(); +// PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( +// "테스트 플랜 카드", +// "플랜 카드 설명", +// now.toString(), +// now.plusHours(2).toString() +// ); +// +// long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); +// long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); +// +// MvcResult result = mockMvc.perform(post("/api/preview-plan/card") +// .param("deviceId", "device-123") +// .param("groupId", "group-456") +// .header("Authorization", accessToken) +// .contentType(MediaType.APPLICATION_JSON) +// .content(objectMapper.writeValueAsString(planCardRequestDto))) +// .andExpect(status().isOk()) +// .andReturn(); +// +// String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); +// +// mockMvc.perform(delete("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId) +// .header("Authorization", accessToken)) +// .andExpect(status().isOk()); +// +// mockMvc.perform(get("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId)) +// .andExpect(status().isNotFound()) +// .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); +// } +//} diff --git a/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java index 0e414307..11d125a9 100644 --- a/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java @@ -98,7 +98,8 @@ void setUp() { // .contentType(MediaType.APPLICATION_JSON) // .param("userId", userId.toString())) // .andExpect(status().isBadRequest()) -// .andExpect(jsonPath("$.message").value("팀 이름은 필수 입력 항목입니다.")); +// .andExpect(jsonPath("$.errorCode").value("TEAM_NAME_NOT_FOUND")) +// .andExpect(jsonPath("$.message").value("팀이름이 비어 있습니다.")); // } // // @Test From 14e06b2337d5038473bc395f24b446d9915a45b4 Mon Sep 17 00:00:00 2001 From: ez23re Date: Mon, 11 Nov 2024 02:15:36 +0900 Subject: [PATCH 28/34] =?UTF-8?q?refactor:=20Team=20=EB=8B=A8=EC=9C=84?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EB=B9=8C=EB=93=9C=EC=8B=A4?= =?UTF-8?q?=ED=8C=A8=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/splanet/splanet/team/service/TeamServiceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/splanet/splanet/team/service/TeamServiceTest.java b/src/test/java/com/splanet/splanet/team/service/TeamServiceTest.java index 4a076576..08fa78b5 100644 --- a/src/test/java/com/splanet/splanet/team/service/TeamServiceTest.java +++ b/src/test/java/com/splanet/splanet/team/service/TeamServiceTest.java @@ -83,7 +83,7 @@ public void testCreateTeam_InvalidInput() { BusinessException exception = assertThrows(BusinessException.class, () -> teamService.createTeam("", 1L) ); - assertEquals(ErrorCode.INVALID_INPUT_VALUE, exception.getErrorCode()); + assertEquals(ErrorCode.TEAM_NAME_NOT_FOUND, exception.getErrorCode()); } @Test From f2499e711bf9110c630cdb2253ed4707fcb7c68f Mon Sep 17 00:00:00 2001 From: kanguk Date: Mon, 11 Nov 2024 02:54:50 +0900 Subject: [PATCH 29/34] =?UTF-8?q?test:=20=ED=8C=80=ED=94=8C=EB=9E=9C=20?= =?UTF-8?q?=ED=86=B5=ED=95=A9=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../teamplan/controller/TeamPlanControllerIntegrationTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java index 7ae26f56..7a6d3421 100644 --- a/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/teamplan/controller/TeamPlanControllerIntegrationTest.java @@ -127,8 +127,7 @@ void setUp() { .header("Authorization", accessToken) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(invalidRequestDto))) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.message").value("공백일 수 없습니다")); + .andExpect(status().isBadRequest()); } @Test From 2d75803c3a170f3e05fbd987a9ea4c16f0bb2451 Mon Sep 17 00:00:00 2001 From: ez23re Date: Tue, 12 Nov 2024 20:45:42 +0900 Subject: [PATCH 30/34] =?UTF-8?q?test:=20=ED=8C=80=20=ED=86=B5=ED=95=A9?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=A4=91=20=EC=84=B1=EA=B3=B5?= =?UTF-8?q?=EC=9D=98=20=EA=B2=BD=EC=9A=B0=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamControllerIntegrationTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java index c52b1d00..b94f6e03 100644 --- a/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java @@ -1,6 +1,8 @@ package com.splanet.splanet.team.controller; import com.fasterxml.jackson.databind.ObjectMapper; +import com.jayway.jsonpath.JsonPath; +import com.splanet.splanet.team.dto.TeamInvitationDto; import com.splanet.splanet.team.entity.*; import com.splanet.splanet.team.repository.TeamInvitationRepository; import com.splanet.splanet.team.repository.TeamRepository; @@ -17,6 +19,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; import org.springframework.transaction.annotation.Transactional; import static org.assertj.core.api.Assertions.assertThat; @@ -122,4 +125,33 @@ void setUp() { .param("nickname", "invitedUser")) .andExpect(status().isForbidden()); } + + @Test + void 팀_생성_성공() throws Exception { + mockMvc.perform(post("/api/teams") + .header("Authorization", accessToken) + .param("teamName", "New Team")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.teamName").value("New Team")) + .andExpect(jsonPath("$.user.nickname").value("adminUser")); + } + + @Test + void 팀_멤버_조회_성공() throws Exception { + mockMvc.perform(get("/api/teams/{teamId}/members", team.getId()) + .header("Authorization", accessToken)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].nickname").value("adminUser")) + .andExpect(jsonPath("$[0].role").value("ADMIN")); + } + + @Test + void 초대_취소_성공() throws Exception { + TeamInvitationDto invitationDto = teamService.inviteUserToTeamByNickname(team.getId(), adminUserId, "invitedUser"); + Long invitationId = invitationDto.getInvitationId(); + + mockMvc.perform(delete("/api/teams/invitation/{invitationId}/cancel", invitationId) + .header("Authorization", accessToken)) + .andExpect(status().isNoContent()); + } } \ No newline at end of file From aac615bdf03cce93a019b6bf91438c6bd2dcfe3d Mon Sep 17 00:00:00 2001 From: ez23re Date: Tue, 12 Nov 2024 21:33:59 +0900 Subject: [PATCH 31/34] =?UTF-8?q?chore:=20splanet-test.log=20=EC=BB=A4?= =?UTF-8?q?=EB=B0=8B=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- splanet-test.log | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 splanet-test.log diff --git a/splanet-test.log b/splanet-test.log deleted file mode 100644 index e69de29b..00000000 From 5cfdbd250f06fd3d09a3dd3419d8838189c6df52 Mon Sep 17 00:00:00 2001 From: ez23re Date: Wed, 13 Nov 2024 02:38:15 +0900 Subject: [PATCH 32/34] =?UTF-8?q?test:=20=ED=8C=80=20=ED=86=B5=ED=95=A9?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=204=EA=B0=9C=EC=9D=98=20=EA=B2=BD?= =?UTF-8?q?=EC=9A=B0=20=EC=B6=94=EA=B0=80(=EA=B3=84=EC=86=8D)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamControllerIntegrationTest.java | 77 +++++++++++++++++-- 1 file changed, 72 insertions(+), 5 deletions(-) diff --git a/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java index b94f6e03..7ea2d6f4 100644 --- a/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java @@ -1,7 +1,6 @@ package com.splanet.splanet.team.controller; import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.JsonPath; import com.splanet.splanet.team.dto.TeamInvitationDto; import com.splanet.splanet.team.entity.*; import com.splanet.splanet.team.repository.TeamInvitationRepository; @@ -16,14 +15,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.HttpHeaders; -import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.transaction.annotation.Transactional; +import java.util.Optional; + import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -154,4 +151,74 @@ void setUp() { .header("Authorization", accessToken)) .andExpect(status().isNoContent()); } + + @Test + void 유저_권한_수정_성공() throws Exception { + TeamInvitationDto invitationDto = teamService.inviteUserToTeamByNickname(team.getId(), adminUserId, "invitedUser"); + Long invitationId = invitationDto.getInvitationId(); + + String invitedUserToken = "Bearer " + jwtTokenProvider.createAccessToken(invitedUserId); + + mockMvc.perform(put("/api/teams/invitation/{invitationId}/response", invitationId) + .header("Authorization", invitedUserToken) + .param("isAccepted", "true")) + .andExpect(status().isNoContent()); + + mockMvc.perform(put("/api/teams/{teamId}/users/{userId}/role", team.getId(), invitedUserId) + .header("Authorization", accessToken)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.userId").value(invitedUserId)) + .andExpect(jsonPath("$.role").value("ADMIN")); + + TeamUserRelation updatedRelation = teamUserRelationRepository.findByTeamAndUser(team, userRepository.findById(invitedUserId).get()).get(); + assertThat(updatedRelation.getRole()).isEqualTo(UserTeamRole.ADMIN); + } + + @Test + void 초대_수락_성공() throws Exception { + TeamInvitationDto invitationDto = teamService.inviteUserToTeamByNickname(team.getId(), adminUserId, "invitedUser"); + Long invitationId = invitationDto.getInvitationId(); + + String invitedUserToken = "Bearer " + jwtTokenProvider.createAccessToken(invitedUserId); + + mockMvc.perform(put("/api/teams/invitation/{invitationId}/response", invitationId) + .header("Authorization", invitedUserToken) + .param("isAccepted", "true")) + .andExpect(status().isNoContent()); + + TeamInvitation updatedInvitation = teamInvitationRepository.findById(invitationId).orElseThrow(); + assertThat(updatedInvitation.getStatus()).isEqualTo(InvitationStatus.ACCEPTED); + + TeamUserRelation userRelation = teamUserRelationRepository.findByTeamAndUser(team, userRepository.findById(invitedUserId).get()).orElseThrow(); + assertThat(userRelation.getUser().getId()).isEqualTo(invitedUserId); + } + + @Test + void 유저_내보내기_실패_권한없음() throws Exception { + User nonAdminUser = User.builder() + .nickname("nonAdminUser") + .profileImage("nonAdmin.png") + .build(); + userRepository.save(nonAdminUser); + String nonAdminToken = "Bearer " + jwtTokenProvider.createAccessToken(nonAdminUser.getId()); + + mockMvc.perform(delete("/api/teams/{teamId}/users/{userId}", team.getId(), invitedUserId) + .header("Authorization", nonAdminToken)) + .andExpect(status().isForbidden()); + } + + @Test + void 유저_내보내기_성공() throws Exception { + // 초대된 유저를 팀에 추가 + TeamInvitationDto invitationDto = teamService.inviteUserToTeamByNickname(team.getId(), adminUserId, "invitedUser"); + teamService.handleInvitationResponse(invitationDto.getInvitationId(), invitedUserId, true); + + // 내보내기 요청 + mockMvc.perform(delete("/api/teams/{teamId}/users/{userId}", team.getId(), invitedUserId) + .header("Authorization", accessToken)) + .andExpect(status().isNoContent()); + // 팀에서 유저가 제거되었는지 확인 + Optional userRelation = teamUserRelationRepository.findByTeamAndUser(team, userRepository.findById(invitedUserId).get()); + assertThat(userRelation).isEmpty(); + } } \ No newline at end of file From 0d11796b35bc8a58e78853a6732757eb151a3248 Mon Sep 17 00:00:00 2001 From: ez23re Date: Wed, 13 Nov 2024 02:54:42 +0900 Subject: [PATCH 33/34] =?UTF-8?q?test:=20=ED=8C=80=20=ED=86=B5=ED=95=A9?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=8B=A4=ED=8C=A8=EA=B2=BD?= =?UTF-8?q?=EC=9A=B0=EB=8F=84=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TeamControllerIntegrationTest.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java index 7ea2d6f4..e1750e7f 100644 --- a/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/team/controller/TeamControllerIntegrationTest.java @@ -221,4 +221,78 @@ void setUp() { Optional userRelation = teamUserRelationRepository.findByTeamAndUser(team, userRepository.findById(invitedUserId).get()); assertThat(userRelation).isEmpty(); } + + @Test + void 유저_내보내기_실패_팀에없는유저() throws Exception { + User notInTeamUser = User.builder() + .nickname("notInTeamUser") + .profileImage("notInTeamUser.png") + .build(); + userRepository.save(notInTeamUser); + String notInTeamUserToken = "Bearer " + jwtTokenProvider.createAccessToken(notInTeamUser.getId()); + + mockMvc.perform(delete("/api/teams/{teamId}/users/{userId}", team.getId(), notInTeamUser.getId()) + .header("Authorization", accessToken)) + .andExpect(status().isNotFound()); + } + + @Test + void 유저_내보내기_실패_팀이없는경우() throws Exception { + Long invalidTeamId = 999L; + + mockMvc.perform(delete("/api/teams/{teamId}/users/{userId}", invalidTeamId, invitedUserId) + .header("Authorization", accessToken)) + .andExpect(status().isNotFound()); + } + + @Test + void 초대_수락_실패_초대가이미수락됨() throws Exception { + TeamInvitationDto invitationDto = teamService.inviteUserToTeamByNickname(team.getId(), adminUserId, "invitedUser"); + Long invitationId = invitationDto.getInvitationId(); + teamService.handleInvitationResponse(invitationId, invitedUserId, true); + + String invitedUserToken = "Bearer " + jwtTokenProvider.createAccessToken(invitedUserId); + mockMvc.perform(put("/api/teams/invitation/{invitationId}/response", invitationId) + .header("Authorization", invitedUserToken) + .param("isAccepted", "true")) + .andExpect(status().isBadRequest()); + } + + @Test + void 유저_권한_수정_실패_관리자권한없음() throws Exception { + User nonAdminUser = User.builder() + .nickname("nonAdminUser") + .profileImage("nonAdmin.png") + .build(); + userRepository.save(nonAdminUser); + String nonAdminToken = "Bearer " + jwtTokenProvider.createAccessToken(nonAdminUser.getId()); + + mockMvc.perform(put("/api/teams/{teamId}/users/{userId}/role", team.getId(), invitedUserId) + .header("Authorization", nonAdminToken)) + .andExpect(status().isForbidden()); + } + + @Test + void 초대_취소_실패_권한없음() throws Exception { + User nonInvitedUser = User.builder() + .nickname("nonInvitedUser") + .profileImage("nonInvited.png") + .build(); + userRepository.save(nonInvitedUser); + String nonInvitedUserToken = "Bearer " + jwtTokenProvider.createAccessToken(nonInvitedUser.getId()); + + TeamInvitationDto invitationDto = teamService.inviteUserToTeamByNickname(team.getId(), adminUserId, "invitedUser"); + Long invitationId = invitationDto.getInvitationId(); + + mockMvc.perform(delete("/api/teams/invitation/{invitationId}/cancel", invitationId) + .header("Authorization", nonInvitedUserToken)) + .andExpect(status().isForbidden()); + } + + @Test + void 팀_생성_실패_필수파라미터누락() throws Exception { + mockMvc.perform(post("/api/teams") + .header("Authorization", accessToken)) + .andExpect(status().isBadRequest()); + } } \ No newline at end of file From 9035fe609d48af22876e3bc62c6251afb4d8330a Mon Sep 17 00:00:00 2001 From: ez23re Date: Wed, 13 Nov 2024 16:46:55 +0900 Subject: [PATCH 34/34] =?UTF-8?q?test:=20=ED=94=84=EB=A6=AC=ED=93=A8?= =?UTF-8?q?=ED=94=8C=EB=9E=9C=20=ED=86=B5=ED=95=A9=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PreviewPlanControllerIntegrationTest.java | 392 +++++++----------- 1 file changed, 155 insertions(+), 237 deletions(-) diff --git a/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java b/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java index f2437b8a..c6b72b83 100644 --- a/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java +++ b/src/test/java/com/splanet/splanet/previewplan/controller/PreviewPlanControllerIntegrationTest.java @@ -1,237 +1,155 @@ -//package com.splanet.splanet.previewplan.controller; -// -//import com.fasterxml.jackson.databind.ObjectMapper; -//import com.jayway.jsonpath.JsonPath; -//import com.splanet.splanet.jwt.JwtTokenProvider; -//import com.splanet.splanet.previewplan.dto.PlanCardRequestDto; -//import com.splanet.splanet.previewplan.dto.PlanCardResponseDto; -//import com.splanet.splanet.previewplan.service.PreviewPlanService; -//import com.splanet.splanet.user.entity.User; -//import com.splanet.splanet.user.repository.UserRepository; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Test; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -//import org.springframework.boot.test.context.SpringBootTest; -//import org.springframework.boot.test.mock.mockito.MockBean; -//import org.springframework.data.redis.core.RedisTemplate; -//import org.springframework.http.MediaType; -//import org.springframework.security.test.context.support.WithMockUser; -//import org.springframework.test.web.servlet.MockMvc; -//import org.springframework.test.web.servlet.MvcResult; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.time.LocalDateTime; -//import java.time.ZoneId; -// -//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -// -//@SpringBootTest -//@AutoConfigureMockMvc -//@Transactional -//class PreviewPlanControllerIntegrationTest { -// -// @Autowired -// private MockMvc mockMvc; -// -// @Autowired -// private ObjectMapper objectMapper; -// -// @Autowired -// private PreviewPlanService previewPlanService; -// -// @Autowired -// private JwtTokenProvider jwtTokenProvider; -// -// @Autowired -// private UserRepository userRepository; -// -// @MockBean -// private RedisTemplate redisTemplate; -// -// private String accessToken; -// private Long userId; -// -// @BeforeEach -// void setUp() { -// // 테스트용 유저 생성 -// User user = User.builder() -// .nickname("testuser") -// .profileImage("testimage.png") -// .build(); -// userRepository.save(user); -// userId = user.getId(); -// -// // JWT 토큰 생성 -// accessToken = "Bearer " + jwtTokenProvider.createAccessToken(userId); -// } -// -// @Test -// @WithMockUser -// void 플랜카드_생성_성공() throws Exception { -// LocalDateTime now = LocalDateTime.now(); -// PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( -// "테스트 플랜 카드", -// "플랜 카드 설명", -// now.toString(), -// now.plusHours(2).toString() -// ); -// -// long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); -// long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); -// -// PlanCardResponseDto planCardResponseDto = new PlanCardResponseDto( -// "device-123", -// "group-456", -// "ed0525be", -// "테스트 플랜 카드", -// "플랜 카드 설명", -// startTimestamp, -// endTimestamp -// ); -// -// mockMvc.perform(post("/api/preview-plan/card") -// .param("deviceId", "device-123") -// .param("groupId", "group-456") -// .header("Authorization", accessToken) -// .contentType(MediaType.APPLICATION_JSON) -// .content(objectMapper.writeValueAsString(planCardRequestDto))) -// .andExpect(status().isOk()) -// .andExpect(jsonPath("$.deviceId").value(planCardResponseDto.deviceId())) -// .andExpect(jsonPath("$.groupId").value(planCardResponseDto.groupId())) -// .andExpect(jsonPath("$.title").value(planCardResponseDto.title())) -// .andExpect(jsonPath("$.description").value(planCardResponseDto.description())) -// .andExpect(jsonPath("$.startTimestamp").value(startTimestamp)) -// .andExpect(jsonPath("$.endTimestamp").value(endTimestamp)); -// } -// -// @Test -// @WithMockUser -// void 플랜카드_조회_성공() throws Exception { -// // 현재 시간 설정 -// LocalDateTime now = LocalDateTime.now(); -// PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( -// "테스트 플랜 카드", -// "플랜 카드 설명", -// now.toString(), -// now.plusHours(2).toString() -// ); -// -// long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); -// long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); -// -// MvcResult result = mockMvc.perform(post("/api/preview-plan/card") -// .param("deviceId", "device-123") -// .param("groupId", "group-456") -// .header("Authorization", accessToken) -// .contentType(MediaType.APPLICATION_JSON) -// .content(objectMapper.writeValueAsString(planCardRequestDto))) -// .andExpect(status().isOk()) -// .andReturn(); -// -// String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); -// -// PlanCardResponseDto planCardResponseDto = new PlanCardResponseDto( -// "device-123", -// "group-456", -// cardId, -// "테스트 플랜 카드", -// "플랜 카드 설명", -// startTimestamp, -// endTimestamp -// ); -// -// mockMvc.perform(get("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId)) -// .andExpect(status().isOk()) -// .andExpect(jsonPath("$.deviceId").value(planCardResponseDto.deviceId())) -// .andExpect(jsonPath("$.groupId").value(planCardResponseDto.groupId())) -// .andExpect(jsonPath("$.title").value(planCardResponseDto.title())) -// .andExpect(jsonPath("$.description").value(planCardResponseDto.description())) -// .andExpect(jsonPath("$.startTimestamp").value(startTimestamp)) -// .andExpect(jsonPath("$.endTimestamp").value(endTimestamp)); -// } -// -// @Test -// @WithMockUser -// void 플랜카드_수정_성공() throws Exception { -// LocalDateTime now = LocalDateTime.now(); -// PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( -// "테스트 플랜 카드", -// "플랜 카드 설명", -// now.toString(), -// now.plusHours(2).toString() -// ); -// -// long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); -// long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); -// -// MvcResult result = mockMvc.perform(post("/api/preview-plan/card") -// .param("deviceId", "device-123") -// .param("groupId", "group-456") -// .header("Authorization", accessToken) -// .contentType(MediaType.APPLICATION_JSON) -// .content(objectMapper.writeValueAsString(planCardRequestDto))) -// .andExpect(status().isOk()) -// .andReturn(); -// -// String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); -// -// PlanCardRequestDto updatedPlanCardRequestDto = new PlanCardRequestDto( -// "수정된 플랜 카드", -// "수정된 플랜 카드 설명", -// now.plusHours(1).toString(), -// now.plusHours(3).toString() -// ); -// -// long updatedStartTimestamp = now.plusHours(1).atZone(ZoneId.systemDefault()).toEpochSecond(); -// long updatedEndTimestamp = now.plusHours(3).atZone(ZoneId.systemDefault()).toEpochSecond(); -// -// mockMvc.perform(put("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId) -// .header("Authorization", accessToken) -// .contentType(MediaType.APPLICATION_JSON) -// .content(objectMapper.writeValueAsString(updatedPlanCardRequestDto))) -// .andExpect(status().isOk()) -// .andExpect(jsonPath("$.deviceId").value("device-123")) -// .andExpect(jsonPath("$.groupId").value("group-456")) -// .andExpect(jsonPath("$.title").value(updatedPlanCardRequestDto.title())) -// .andExpect(jsonPath("$.description").value(updatedPlanCardRequestDto.description())) -// .andExpect(jsonPath("$.startTimestamp").value(updatedStartTimestamp)) -// .andExpect(jsonPath("$.endTimestamp").value(updatedEndTimestamp)); -// } -// -// @Test -// @WithMockUser -// void 플랜카드_삭제_성공() throws Exception { -// LocalDateTime now = LocalDateTime.now(); -// PlanCardRequestDto planCardRequestDto = new PlanCardRequestDto( -// "테스트 플랜 카드", -// "플랜 카드 설명", -// now.toString(), -// now.plusHours(2).toString() -// ); -// -// long startTimestamp = now.atZone(ZoneId.systemDefault()).toEpochSecond(); -// long endTimestamp = now.plusHours(2).atZone(ZoneId.systemDefault()).toEpochSecond(); -// -// MvcResult result = mockMvc.perform(post("/api/preview-plan/card") -// .param("deviceId", "device-123") -// .param("groupId", "group-456") -// .header("Authorization", accessToken) -// .contentType(MediaType.APPLICATION_JSON) -// .content(objectMapper.writeValueAsString(planCardRequestDto))) -// .andExpect(status().isOk()) -// .andReturn(); -// -// String cardId = JsonPath.read(result.getResponse().getContentAsString(), "$.cardId"); -// -// mockMvc.perform(delete("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId) -// .header("Authorization", accessToken)) -// .andExpect(status().isOk()); -// -// mockMvc.perform(get("/api/preview-plan/card/{deviceId}/{groupId}/{cardId}", "device-123", "group-456", cardId)) -// .andExpect(status().isNotFound()) -// .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); -// } -//} +package com.splanet.splanet.previewplan.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.splanet.splanet.previewplan.dto.PlanCardRequestDto; +import com.splanet.splanet.previewplan.entity.PlanCard; +import com.splanet.splanet.previewplan.repository.PlanCardRepository; +import com.splanet.splanet.previewplan.repository.PlanGroupRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@Transactional +class PreviewPlanControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private RedisTemplate redisTemplate; + + @Autowired + private PlanCardRepository planCardRepository; + + @Autowired + private PlanGroupRepository planGroupRepository; + + private static final String BASE_URL = "/api/preview-plan"; + + @BeforeEach + void setup() { + redisTemplate.getConnectionFactory().getConnection().flushAll(); + } + + // 테스트에 필요한 샘플 데이터 저장 메서드 + private void saveSamplePlanCard(String deviceId, String groupId, String cardId) { + PlanCard planCard = PlanCard.builder() + .customKey(deviceId + ":" + groupId + ":" + cardId) + .deviceId(deviceId) + .groupId(groupId) + .cardId(cardId) + .title("Sample Title") + .description("Sample Description") + .startDate("2024-01-01") + .endDate("2024-12-31") + .expiration(3600L) + .build(); + planCardRepository.save(planCard); + } + + @Test + void 플랜카드_생성_성공() throws Exception { + PlanCardRequestDto requestDto = new PlanCardRequestDto("Title", "Description", "2024-01-01", "2024-12-31"); + + mockMvc.perform(post(BASE_URL + "/card") + .param("deviceId", "testDevice") + .param("groupId", "testGroup") + .contentType(MediaType.APPLICATION_JSON) + .content(new ObjectMapper().writeValueAsString(requestDto))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.title").value("Title")) + .andExpect(jsonPath("$.description").value("Description")); + } + + @Test + void 플랜카드_조회_성공() throws Exception { + String deviceId = "testDevice"; + String groupId = "testGroup"; + String cardId = "testCard"; + saveSamplePlanCard(deviceId, groupId, cardId); + + mockMvc.perform(get(BASE_URL + "/card/{deviceId}/{groupId}/{cardId}", deviceId, groupId, cardId)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.title").value("Sample Title")); + } + + @Test + void 플랜카드_수정_성공() throws Exception { + String deviceId = "testDevice"; + String groupId = "testGroup"; + String cardId = "testCard"; + saveSamplePlanCard(deviceId, groupId, cardId); + + PlanCardRequestDto updateRequest = new PlanCardRequestDto("Updated Title", "Updated Description", "2024-01-01", "2024-12-31"); + + mockMvc.perform(put(BASE_URL + "/card/{deviceId}/{groupId}/{cardId}", deviceId, groupId, cardId) + .contentType(MediaType.APPLICATION_JSON) + .content(new ObjectMapper().writeValueAsString(updateRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.title").value("Updated Title")) + .andExpect(jsonPath("$.description").value("Updated Description")); + } + + @Test + void 플랜카드_삭제_성공() throws Exception { + String deviceId = "testDevice"; + String groupId = "testGroup"; + String cardId = "testCard"; + saveSamplePlanCard(deviceId, groupId, cardId); + + mockMvc.perform(delete(BASE_URL + "/card/{deviceId}/{groupId}/{cardId}", deviceId, groupId, cardId)) + .andExpect(status().isOk()); + + assertFalse(planCardRepository.findById(deviceId + ":" + groupId + ":" + cardId).isPresent()); + } + + @Test + void 플랜카드_조회_실패_존재하지_않는_카드() throws Exception { + String deviceId = "testDevice"; + String groupId = "testGroup"; + String nonExistentCardId = "nonExistentCard"; + + mockMvc.perform(get(BASE_URL + "/card/{deviceId}/{groupId}/{cardId}", deviceId, groupId, nonExistentCardId)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); + } + + @Test + void 플랜카드_수정_실패_존재하지_않는_카드() throws Exception { + String deviceId = "testDevice"; + String groupId = "testGroup"; + String nonExistentCardId = "nonExistentCard"; + + PlanCardRequestDto updateRequest = new PlanCardRequestDto("Updated Title", "Updated Description", "2024-01-01", "2024-12-31"); + + mockMvc.perform(put(BASE_URL + "/card/{deviceId}/{groupId}/{cardId}", deviceId, groupId, nonExistentCardId) + .contentType(MediaType.APPLICATION_JSON) + .content(new ObjectMapper().writeValueAsString(updateRequest))) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); + } + + @Test + void 플랜카드_삭제_실패_존재하지_않는_카드() throws Exception { + String deviceId = "testDevice"; + String groupId = "testGroup"; + String nonExistentCardId = "nonExistentCard"; + + mockMvc.perform(delete(BASE_URL + "/card/{deviceId}/{groupId}/{cardId}", deviceId, groupId, nonExistentCardId)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("플랜이 존재하지 않습니다.")); + } +} \ No newline at end of file