diff --git a/src/main/java/corecord/dev/domain/chat/application/ChatDbService.java b/src/main/java/corecord/dev/domain/chat/application/ChatDbService.java new file mode 100644 index 0000000..2e4ee75 --- /dev/null +++ b/src/main/java/corecord/dev/domain/chat/application/ChatDbService.java @@ -0,0 +1,67 @@ +package corecord.dev.domain.chat.application; + +import corecord.dev.domain.chat.domain.converter.ChatConverter; +import corecord.dev.domain.chat.domain.entity.Chat; +import corecord.dev.domain.chat.domain.entity.ChatRoom; +import corecord.dev.domain.chat.domain.repository.ChatRepository; +import corecord.dev.domain.chat.domain.repository.ChatRoomRepository; +import corecord.dev.domain.user.domain.entity.User; +import corecord.dev.domain.user.domain.repository.UserRepository; +import corecord.dev.domain.chat.exception.ChatException; +import corecord.dev.domain.chat.status.ChatErrorStatus; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +@RequiredArgsConstructor +public class ChatDbService { + + private final ChatRepository chatRepository; + private final ChatRoomRepository chatRoomRepository; + private final UserRepository userRepository; + + @Transactional + public ChatRoom createChatRoom(User user) { + ChatRoom chatRoom = ChatConverter.toChatRoomEntity(user); + return chatRoomRepository.save(chatRoom); + } + + @Transactional + public Chat saveChat(int author, String content, ChatRoom chatRoom) { + Chat chat = ChatConverter.toChatEntity(author, content, chatRoom); + return chatRepository.save(chat); + } + + public ChatRoom findChatRoomById(Long chatRoomId, User user) { + return chatRoomRepository.findByChatRoomIdAndUser(chatRoomId, user) + .orElseThrow(() -> new ChatException(ChatErrorStatus.CHAT_ROOM_NOT_FOUND)); + } + + public User findUserById(Long userId) { + return userRepository.findById(userId) + .orElseThrow(() -> new ChatException(ChatErrorStatus.CHAT_ROOM_NOT_FOUND)); + } + + @Transactional + public void deleteChatRoom(ChatRoom chatRoom) { + chatRepository.deleteByChatRoomId(chatRoom.getChatRoomId()); + chatRoomRepository.delete(chatRoom); + } + + public List findChatsByChatRoom(ChatRoom chatRoom) { + return chatRepository.findByChatRoomOrderByChatId(chatRoom); + } + + @Transactional + public void updateUserTmpChat(User user, Long chatRoomId) { + user.updateTmpChat(chatRoomId); + } + + @Transactional + public void deleteUserTmpChat(User user) { + user.deleteTmpChat(); + } +} diff --git a/src/main/java/corecord/dev/domain/chat/application/ChatService.java b/src/main/java/corecord/dev/domain/chat/application/ChatService.java index f8a9d76..fdc60db 100644 --- a/src/main/java/corecord/dev/domain/chat/application/ChatService.java +++ b/src/main/java/corecord/dev/domain/chat/application/ChatService.java @@ -30,9 +30,7 @@ @RequiredArgsConstructor public class ChatService { - private final ChatRoomRepository chatRoomRepository; - private final ChatRepository chatRepository; - private final UserRepository userRepository; + private final ChatDbService chatDbService; private final ClovaService clovaService; /* @@ -40,16 +38,15 @@ public class ChatService { * @param userId * @return chatRoomDto */ - @Transactional public ChatResponse.ChatRoomDto createChatRoom(Long userId) { - User user = findUserById(userId); + User user = chatDbService.findUserById(userId); // 채팅방 생성 - ChatRoom chatRoom = ChatConverter.toChatRoomEntity(user); - chatRoomRepository.save(chatRoom); + ChatRoom chatRoom = chatDbService.createChatRoom(user); // 첫번째 채팅 생성 - "안녕하세요! {nickName}님! {nickName}님의 경험이 궁금해요. {nickName}님의 경험을 들려주세요!" - Chat firstChat = createFirstChat(user, chatRoom); + String firstChatContent = String.format("안녕하세요! %s님\n오늘은 어떤 경험을 했나요?\n저와 함께 정리해보아요!", user.getNickName()); + Chat firstChat = chatDbService.saveChat(0, firstChatContent, chatRoom); return ChatConverter.toChatRoomDto(chatRoom, firstChat); } @@ -60,24 +57,22 @@ public ChatResponse.ChatRoomDto createChatRoom(Long userId) { * @param chatDto * @return */ - @Transactional public ChatResponse.ChatsDto createChat(Long userId, Long chatRoomId, ChatRequest.ChatDto chatDto) { - User user = findUserById(userId); - ChatRoom chatRoom = findChatRoomById(chatRoomId, user); + User user = chatDbService.findUserById(userId); + ChatRoom chatRoom = chatDbService.findChatRoomById(chatRoomId, user); // 사용자 채팅 생성 - Chat chat = ChatConverter.toChatEntity(1, chatDto.getContent(), chatRoom); - chatRepository.save(chat); + chatDbService.saveChat(1, chatDto.getContent(), chatRoom); // 가이드이면 가이드 채팅 생성 - if(chatDto.isGuide()) { + if (chatDto.isGuide()) { checkGuideChat(chatRoom); return generateGuideChats(chatRoom); } // AI 답변 생성 String aiAnswer = createChatAiAnswer(chatRoom, chatDto.getContent()); - Chat aiChat = chatRepository.save(ChatConverter.toChatEntity(0, aiAnswer, chatRoom)); + Chat aiChat = chatDbService.saveChat(0, aiAnswer, chatRoom); return ChatConverter.toChatsDto(List.of(aiChat)); } @@ -89,9 +84,9 @@ public ChatResponse.ChatsDto createChat(Long userId, Long chatRoomId, ChatReques * @return chatListDto */ public ChatResponse.ChatListDto getChatList(Long userId, Long chatRoomId) { - User user = findUserById(userId); - ChatRoom chatRoom = findChatRoomById(chatRoomId, user); - List chatList = chatRepository.findByChatRoomOrderByChatId(chatRoom); + User user = chatDbService.findUserById(userId); + ChatRoom chatRoom = chatDbService.findChatRoomById(chatRoomId, user); + List chatList = chatDbService.findChatsByChatRoom(chatRoom); return ChatConverter.toChatListDto(chatList); } @@ -101,15 +96,13 @@ public ChatResponse.ChatListDto getChatList(Long userId, Long chatRoomId) { * @param userId * @param chatRoomId */ - @Transactional public void deleteChatRoom(Long userId, Long chatRoomId) { - User user = findUserById(userId); - ChatRoom chatRoom = findChatRoomById(chatRoomId, user); + User user = chatDbService.findUserById(userId); + ChatRoom chatRoom = chatDbService.findChatRoomById(chatRoomId, user); // 임시 저장된 ChatRoom 인지 확인 후 삭제 checkTmpChat(user, chatRoom); - chatRepository.deleteByChatRoomId(chatRoomId); - chatRoomRepository.delete(chatRoom); + chatDbService.deleteChatRoom(chatRoom); } /* @@ -119,9 +112,9 @@ public void deleteChatRoom(Long userId, Long chatRoomId) { * @return chatSummaryDto */ public ChatResponse.ChatSummaryDto getChatSummary(Long userId, Long chatRoomId) { - User user = findUserById(userId); - ChatRoom chatRoom = findChatRoomById(chatRoomId, user); - List chatList = chatRepository.findByChatRoomOrderByChatId(chatRoom); + User user = chatDbService.findUserById(userId); + ChatRoom chatRoom = chatDbService.findChatRoomById(chatRoomId, user); + List chatList = chatDbService.findChatsByChatRoom(chatRoom); // 사용자 입력 없이 저장하려는 경우 체크 validateChatList(chatList); @@ -141,13 +134,13 @@ public ChatResponse.ChatSummaryDto getChatSummary(Long userId, Long chatRoomId) */ @Transactional public ChatResponse.ChatTmpDto getChatTmp(Long userId) { - User user = findUserById(userId); - if(user.getTmpChat() == null) { + User user = chatDbService.findUserById(userId); + if (user.getTmpChat() == null) { return ChatConverter.toNotExistingChatTmpDto(); } // 임시 채팅 제거 후 반환 Long chatRoomId = user.getTmpChat(); - user.deleteTmpChat(); + chatDbService.deleteUserTmpChat(user); return ChatConverter.toExistingChatTmpDto(chatRoomId); } @@ -158,27 +151,25 @@ public ChatResponse.ChatTmpDto getChatTmp(Long userId) { */ @Transactional public void saveChatTmp(Long userId, Long chatRoomId) { - User user = findUserById(userId); - ChatRoom chatRoom = findChatRoomById(chatRoomId, user); + User user = chatDbService.findUserById(userId); + ChatRoom chatRoom = chatDbService.findChatRoomById(chatRoomId, user); // 이미 임시 저장된 채팅방이 있는 경우 - if(user.getTmpChat() != null) { + if (user.getTmpChat() != null) { throw new ChatException(ChatErrorStatus.TMP_CHAT_EXIST); } - user.updateTmpChat(chatRoom.getChatRoomId()); + chatDbService.updateUserTmpChat(user, chatRoom.getChatRoomId()); } private static void checkGuideChat(ChatRoom chatRoom) { - if(chatRoom.getChatList().size() > 2) { + if (chatRoom.getChatList().size() > 2) { throw new ChatException(ChatErrorStatus.INVALID_GUIDE_CHAT); } } private ChatResponse.ChatsDto generateGuideChats(ChatRoom chatRoom) { - Chat guideChat1 = ChatConverter.toChatEntity(0, "걱정 마세요!\n저와 대화하다 보면 경험이 정리될 거예요\uD83D\uDCDD", chatRoom); - Chat guideChat2 = ChatConverter.toChatEntity(0, "오늘은 어떤 경험을 했나요?\n상황과 해결한 문제를 말해주세요!", chatRoom); - chatRepository.save(guideChat1); - chatRepository.save(guideChat2); + Chat guideChat1 = chatDbService.saveChat(0, "걱정 마세요!\n저와 대화하다 보면 경험이 정리될 거예요\uD83D\uDCDD", chatRoom); + Chat guideChat2 = chatDbService.saveChat(0, "오늘은 어떤 경험을 했나요?\n상황과 해결한 문제를 말해주세요!", chatRoom); return ChatConverter.toChatsDto(List.of(guideChat1, guideChat2)); } @@ -197,7 +188,7 @@ private static void validateResponse(ChatSummaryAiResponse response) { } private static void validateChatList(List chatList) { - if(chatList.size() <= 1) { + if (chatList.size() <= 1) { throw new ChatException(ChatErrorStatus.NO_RECORD); } } @@ -218,36 +209,18 @@ private ChatSummaryAiResponse parseChatSummaryResponse(String aiResponse) { } private void checkTmpChat(User user, ChatRoom chatRoom) { - if(user.getTmpChat() == null) { + if (user.getTmpChat() == null) { return; } - if(user.getTmpChat().equals(chatRoom.getChatRoomId())) { + if (user.getTmpChat().equals(chatRoom.getChatRoomId())) { user.deleteTmpChat(); } } private String createChatAiAnswer(ChatRoom chatRoom, String userInput) { - List chatHistory = chatRepository.findByChatRoomOrderByChatId(chatRoom); + List chatHistory = chatDbService.findChatsByChatRoom(chatRoom); ClovaRequest clovaRequest = ClovaRequest.createChatRequest(chatHistory, userInput); return clovaService.generateAiResponse(clovaRequest); } - private ChatRoom findChatRoomById(Long chatRoomId, User user) { - return chatRoomRepository.findByChatRoomIdAndUser(chatRoomId, user) - .orElseThrow(() -> new ChatException(ChatErrorStatus.CHAT_ROOM_NOT_FOUND)); - } - - private Chat createFirstChat(User user, ChatRoom chatRoom) { - String nickName = user.getNickName(); - String firstChatContent = String.format("안녕하세요! %s님\n오늘은 어떤 경험을 했나요?\n저와 함께 정리해보아요!", nickName); - Chat chat = ChatConverter.toChatEntity(0, firstChatContent, chatRoom); - chatRepository.save(chat); - return chat; - } - - private User findUserById(Long userId) { - return userRepository.findById(userId) - .orElseThrow(() -> new GeneralException(ErrorStatus.UNAUTHORIZED)); - } - } diff --git a/src/main/java/corecord/dev/domain/folder/domain/dto/request/FolderRequest.java b/src/main/java/corecord/dev/domain/folder/domain/dto/request/FolderRequest.java index 3e21fb0..d70835d 100644 --- a/src/main/java/corecord/dev/domain/folder/domain/dto/request/FolderRequest.java +++ b/src/main/java/corecord/dev/domain/folder/domain/dto/request/FolderRequest.java @@ -2,18 +2,22 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; public class FolderRequest { @Data @Builder + @AllArgsConstructor @NoArgsConstructor public static class FolderDto { @NotBlank(message = "폴더 명을 입력해주세요.") private String title; } @Data @Builder + @AllArgsConstructor @NoArgsConstructor public static class FolderUpdateDto { @NotNull(message = "수정할 폴더 id를 입력해주세요.") private Long folderId; diff --git a/src/test/java/corecord/dev/chat/service/ChatServiceTest.java b/src/test/java/corecord/dev/chat/service/ChatServiceTest.java index 481e355..0d7d0b3 100644 --- a/src/test/java/corecord/dev/chat/service/ChatServiceTest.java +++ b/src/test/java/corecord/dev/chat/service/ChatServiceTest.java @@ -1,18 +1,16 @@ package corecord.dev.chat.service; +import corecord.dev.domain.chat.application.ChatDbService; +import corecord.dev.domain.chat.application.ChatService; import corecord.dev.domain.chat.domain.dto.request.ChatRequest; import corecord.dev.domain.chat.domain.dto.response.ChatResponse; import corecord.dev.domain.chat.domain.entity.Chat; import corecord.dev.domain.chat.domain.entity.ChatRoom; import corecord.dev.domain.chat.exception.ChatException; -import corecord.dev.domain.chat.domain.repository.ChatRepository; -import corecord.dev.domain.chat.domain.repository.ChatRoomRepository; -import corecord.dev.domain.chat.application.ChatService; -import corecord.dev.domain.chat.infra.clova.dto.request.ClovaRequest; import corecord.dev.domain.chat.infra.clova.application.ClovaService; +import corecord.dev.domain.chat.infra.clova.dto.request.ClovaRequest; import corecord.dev.domain.user.domain.entity.Status; import corecord.dev.domain.user.domain.entity.User; -import corecord.dev.domain.user.domain.repository.UserRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; @@ -38,54 +36,48 @@ class ChatServiceTest { private ChatService chatService; @Mock - private ChatRoomRepository chatRoomRepository; - - @Mock - private ChatRepository chatRepository; - - @Mock - private UserRepository userRepository; + private ChatDbService chatDbService; @Mock private ClovaService clovaService; private User user; - private ChatRoom chatRoom; @BeforeEach void setUp() { user = createTestUser(); chatRoom = createTestChatRoom(); - } @Test @DisplayName("채팅방 생성 테스트") void createChatRoom() { // Given - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.createChatRoom(user)).thenReturn(chatRoom); + when(chatDbService.saveChat(anyInt(), anyString(), any(ChatRoom.class))) + .thenAnswer(invocation -> createTestChat(invocation.getArgument(1), invocation.getArgument(0))); // When ChatResponse.ChatRoomDto result = chatService.createChatRoom(user.getUserId()); // Then - verify(chatRoomRepository).save(any(ChatRoom.class)); - verify(chatRepository).save(any(Chat.class)); + verify(chatDbService).createChatRoom(user); + verify(chatDbService).saveChat(0, "안녕하세요! testUser님\n오늘은 어떤 경험을 했나요?\n저와 함께 정리해보아요!", chatRoom); assertEquals(result.getFirstChat(), "안녕하세요! testUser님\n오늘은 어떤 경험을 했나요?\n저와 함께 정리해보아요!"); } @Test @DisplayName("채팅 조회 테스트") - void getChatList() throws NoSuchFieldException, IllegalAccessException { + void getChatList() { // Given Chat userChat = createTestChat("userChat", 1); Chat aiChat = createTestChat("aiChat", 0); - - when(chatRepository.findByChatRoomOrderByChatId(chatRoom)).thenReturn(List.of(userChat, aiChat)); - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); - when(chatRoomRepository.findByChatRoomIdAndUser(chatRoom.getChatRoomId(), user)).thenReturn(Optional.of(chatRoom)); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.findChatRoomById(chatRoom.getChatRoomId(), user)).thenReturn(chatRoom); + when(chatDbService.findChatsByChatRoom(chatRoom)).thenReturn(List.of(userChat, aiChat)); // When ChatResponse.ChatListDto result = chatService.getChatList(user.getUserId(), chatRoom.getChatRoomId()); @@ -109,8 +101,10 @@ void createChatWithGuide() { .content("어떤 경험을 말해야 할지 모르겠어요.") .build(); - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); - when(chatRoomRepository.findByChatRoomIdAndUser(chatRoom.getChatRoomId(), user)).thenReturn(Optional.of(chatRoom)); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.findChatRoomById(chatRoom.getChatRoomId(), user)).thenReturn(chatRoom); + when(chatDbService.saveChat(anyInt(), anyString(), any(ChatRoom.class))) + .thenAnswer(invocation -> createTestChat(invocation.getArgument(1), invocation.getArgument(0))); // When ChatResponse.ChatsDto result = chatService.createChat( @@ -120,7 +114,7 @@ void createChatWithGuide() { ); // Then - verify(chatRepository, times(3)).save(any(Chat.class)); // 사용자 입력 1개, 가이드 2개 + verify(chatDbService, times(3)).saveChat(anyInt(), anyString(), eq(chatRoom)); // 사용자 입력 1개, 가이드 2개 assertEquals(result.getChats().size(), 2); // Guide 메시지는 두 개 생성 assertEquals(result.getChats().get(0).getContent(), "걱정 마세요!\n저와 대화하다 보면 경험이 정리될 거예요\uD83D\uDCDD"); assertEquals(result.getChats().get(1).getContent(), "오늘은 어떤 경험을 했나요?\n상황과 해결한 문제를 말해주세요!"); @@ -134,9 +128,10 @@ void createChatWithSuccess() { .content("테스트 입력") .build(); - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); - when(chatRoomRepository.findByChatRoomIdAndUser(chatRoom.getChatRoomId(), user)).thenReturn(Optional.of(chatRoom)); - when(chatRepository.save(any(Chat.class))).thenAnswer(invocation -> invocation.getArgument(0)); // 저장된 Chat 객체 반환 + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.findChatRoomById(chatRoom.getChatRoomId(), user)).thenReturn(chatRoom); + when(chatDbService.saveChat(anyInt(), anyString(), any(ChatRoom.class))) + .thenAnswer(invocation -> createTestChat(invocation.getArgument(1), invocation.getArgument(0))); when(clovaService.generateAiResponse(any(ClovaRequest.class))).thenReturn("AI의 예상 응답"); // When @@ -147,7 +142,7 @@ void createChatWithSuccess() { ); // Then - verify(chatRepository, times(2)).save(any(Chat.class)); // 사용자 입력 1개, AI 응답 1개 + verify(chatDbService, times(2)).saveChat(anyInt(), anyString(), eq(chatRoom)); // 사용자 입력 1개, AI 응답 1개 assertEquals(result.getChats().size(), 1); assertEquals(result.getChats().getFirst().getContent(), "AI의 예상 응답"); } @@ -159,7 +154,7 @@ class ChatSummaryTests { @Test @DisplayName("AI 응답 성공 시") - void validAiResponse() throws NoSuchFieldException, IllegalAccessException { + void validAiResponse() { // Given List chatList = List.of( createTestChat("userChat1", 1), @@ -167,9 +162,9 @@ void validAiResponse() throws NoSuchFieldException, IllegalAccessException { createTestChat("userChat2", 1) ); - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); - when(chatRoomRepository.findByChatRoomIdAndUser(chatRoom.getChatRoomId(), user)).thenReturn(Optional.of(chatRoom)); - when(chatRepository.findByChatRoomOrderByChatId(chatRoom)).thenReturn(chatList); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.findChatRoomById(chatRoom.getChatRoomId(), user)).thenReturn(chatRoom); + when(chatDbService.findChatsByChatRoom(chatRoom)).thenReturn(chatList); when(clovaService.generateAiResponse(any(ClovaRequest.class))) .thenReturn("{\"title\":\"요약 제목\",\"content\":\"요약 내용\"}"); @@ -183,16 +178,16 @@ void validAiResponse() throws NoSuchFieldException, IllegalAccessException { @Test @DisplayName("AI 응답이 빈 경우") - void emptyAiResponse() throws NoSuchFieldException, IllegalAccessException { + void emptyAiResponse() { // Given List chatList = List.of( createTestChat("userChat1", 1), createTestChat("aiChat1", 0) ); - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); - when(chatRoomRepository.findByChatRoomIdAndUser(chatRoom.getChatRoomId(), user)).thenReturn(Optional.of(chatRoom)); - when(chatRepository.findByChatRoomOrderByChatId(chatRoom)).thenReturn(chatList); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.findChatRoomById(chatRoom.getChatRoomId(), user)).thenReturn(chatRoom); + when(chatDbService.findChatsByChatRoom(chatRoom)).thenReturn(chatList); when(clovaService.generateAiResponse(any(ClovaRequest.class))) .thenReturn("{\"title\":\"\",\"content\":\"\"}"); // 빈 응답 @@ -202,7 +197,7 @@ void emptyAiResponse() throws NoSuchFieldException, IllegalAccessException { @Test @DisplayName("AI 응답이 긴 경우 예외 발생 (제목 50자 초과)") - void longAiTitle() throws NoSuchFieldException, IllegalAccessException { + void longAiTitle() { // Given List chatList = List.of( createTestChat("userChat1", 1), @@ -210,9 +205,9 @@ void longAiTitle() throws NoSuchFieldException, IllegalAccessException { ); String longTitle = "a".repeat(51); // 51자 제목 생성 - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); - when(chatRoomRepository.findByChatRoomIdAndUser(chatRoom.getChatRoomId(), user)).thenReturn(Optional.of(chatRoom)); - when(chatRepository.findByChatRoomOrderByChatId(chatRoom)).thenReturn(chatList); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.findChatRoomById(chatRoom.getChatRoomId(), user)).thenReturn(chatRoom); + when(chatDbService.findChatsByChatRoom(chatRoom)).thenReturn(chatList); when(clovaService.generateAiResponse(any(ClovaRequest.class))) .thenReturn(String.format("{\"title\":\"%s\",\"content\":\"정상 내용\"}", longTitle)); // 50자 초과 제목 @@ -222,7 +217,7 @@ void longAiTitle() throws NoSuchFieldException, IllegalAccessException { @Test @DisplayName("AI 응답이 긴 경우 예외 발생 (내용 500자 초과)") - void longAiResponse() throws NoSuchFieldException, IllegalAccessException { + void longAiResponse() { // Given List chatList = List.of( createTestChat("userChat1", 1), @@ -230,9 +225,9 @@ void longAiResponse() throws NoSuchFieldException, IllegalAccessException { ); String longContent = "a".repeat(501); // 501자 응답 생성 - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); - when(chatRoomRepository.findByChatRoomIdAndUser(chatRoom.getChatRoomId(), user)).thenReturn(Optional.of(chatRoom)); - when(chatRepository.findByChatRoomOrderByChatId(chatRoom)).thenReturn(chatList); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.findChatRoomById(chatRoom.getChatRoomId(), user)).thenReturn(chatRoom); + when(chatDbService.findChatsByChatRoom(chatRoom)).thenReturn(chatList); when(clovaService.generateAiResponse(any(ClovaRequest.class))) .thenReturn(String.format("{\"title\":\"정상 제목\",\"content\":\"%s\"}", longContent)); // 500자 초과 내용 @@ -249,15 +244,16 @@ class ChatTmpTests { @DisplayName("저장 성공") void saveChatTmp() { // Given - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); - when(chatRoomRepository.findByChatRoomIdAndUser(chatRoom.getChatRoomId(), user)).thenReturn(Optional.of(chatRoom)); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.findChatRoomById(chatRoom.getChatRoomId(), user)).thenReturn(chatRoom); // When chatService.saveChatTmp(user.getUserId(), chatRoom.getChatRoomId()); // Then - assertEquals(user.getTmpChat(), chatRoom.getChatRoomId()); - verify(userRepository).findById(user.getUserId()); + verify(chatDbService).findUserById(user.getUserId()); + verify(chatDbService).findChatRoomById(chatRoom.getChatRoomId(), user); + verify(chatDbService).updateUserTmpChat(user, chatRoom.getChatRoomId()); } @Test @@ -265,8 +261,8 @@ void saveChatTmp() { void saveChatTmpFailsWhenTmpChatExists() { // Given user.updateTmpChat(chatRoom.getChatRoomId()); - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); - when(chatRoomRepository.findByChatRoomIdAndUser(chatRoom.getChatRoomId(), user)).thenReturn(Optional.of(chatRoom)); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); + when(chatDbService.findChatRoomById(chatRoom.getChatRoomId(), user)).thenReturn(chatRoom); // When & Then assertThrows(ChatException.class, () -> chatService.saveChatTmp(user.getUserId(), chatRoom.getChatRoomId())); @@ -277,7 +273,7 @@ void saveChatTmpFailsWhenTmpChatExists() { void getChatTmp() { // Given user.updateTmpChat(chatRoom.getChatRoomId()); - when(userRepository.findById(user.getUserId())).thenReturn(Optional.of(user)); + when(chatDbService.findUserById(user.getUserId())).thenReturn(user); // When ChatResponse.ChatTmpDto result = chatService.getChatTmp(user.getUserId()); @@ -285,11 +281,11 @@ void getChatTmp() { // Then assertEquals(result.getChatRoomId(), chatRoom.getChatRoomId()); assertTrue(result.isExist()); - verify(userRepository).findById(user.getUserId()); + verify(chatDbService).findUserById(user.getUserId()); } } - private User createTestUser() { + private User createTestUser() { return User.builder() .userId(1L) .providerId("providerId") @@ -310,16 +306,14 @@ private ChatRoom createTestChatRoom() { .build(); } - private Chat createTestChat(String content, int isSystem) throws IllegalAccessException, NoSuchFieldException { - Chat chat = Chat.builder() + private Chat createTestChat(String content, int isSystem) { + Chat chat = Chat.builder() .chatId(1L) .author(isSystem) .content(content) .chatRoom(chatRoom) .build(); - Field createdAtField = Chat.class.getSuperclass().getDeclaredField("createdAt"); - createdAtField.setAccessible(true); - createdAtField.set(chat, LocalDateTime.now()); + chat.setCreatedAt(LocalDateTime.now()); return chat; } }