diff --git a/src/test/java/com/seniors/domain/chat/controller/ChatMessageControllerTest.java b/src/test/java/com/seniors/domain/chat/controller/ChatMessageControllerTest.java new file mode 100644 index 0000000..e1b910c --- /dev/null +++ b/src/test/java/com/seniors/domain/chat/controller/ChatMessageControllerTest.java @@ -0,0 +1,119 @@ +package com.seniors.domain.chat.controller; + +import com.seniors.config.security.CustomUserDetails; +import com.seniors.domain.chat.dto.ChatMessageDto; +import com.seniors.domain.chat.entity.ChatRoom; +import com.seniors.domain.chat.repository.ChatMessageRepository; +import com.seniors.domain.chat.repository.ChatRoomRepository; +import com.seniors.domain.config.WithMockCustomUser; +import com.seniors.domain.users.entity.Users; +import com.seniors.domain.users.repository.UsersRepository; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +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.web.server.LocalServerPort; +import org.springframework.messaging.converter.MappingJackson2MessageConverter; +import org.springframework.messaging.simp.stomp.StompFrameHandler; +import org.springframework.messaging.simp.stomp.StompHeaders; +import org.springframework.messaging.simp.stomp.StompSession; +import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.socket.client.standard.StandardWebSocketClient; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; +import org.springframework.web.socket.messaging.WebSocketStompClient; + +import java.lang.reflect.Type; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; + +@ActiveProfiles("dev") +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@EnableWebSocketMessageBroker +@Slf4j +@WithMockCustomUser +class ChatMessageControllerTest { + + @Autowired + private ChatRoomRepository chatRoomRepository; + @Autowired + private UsersRepository usersRepository; + @Autowired + private ChatMessageRepository chatMessageRepository; + private Authentication authentication; + private Users users; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + static final String WEBSOCKET_SUB_URI = "/sub/chat/room/"; + static final String WEBSOCKET_PUB_URI = "/pub/chat/sendMessage"; + + @LocalServerPort + private int port; + + @BeforeEach + void setUp() { + mockMvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .apply(springSecurity()) + .build(); + + authentication = SecurityContextHolder.getContext().getAuthentication(); + CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); + + users = usersRepository.getOneUsers(customUserDetails.getUserId()); + } + @Test + @DisplayName("채팅하기") + public void chatMessageSend() throws Exception { + + // given + WebSocketStompClient stompClient = new WebSocketStompClient(new StandardWebSocketClient()); + stompClient.setMessageConverter(new MappingJackson2MessageConverter()); + + StompSession stompSession = stompClient.connect("ws://localhost:" + port + "/api/chat", new StompSessionHandlerAdapter() { + }).get(1, TimeUnit.SECONDS); + + ChatRoom chatRoom = new ChatRoom(); + chatRoomRepository.save(chatRoom); + ChatMessageDto.ChatMessageTransDto chatMessageTransDto = ChatMessageDto.ChatMessageTransDto.of(chatRoom.getId(), users.getId(), "채팅 내용입니다."); + + CompletableFuture subscribeFuture = new CompletableFuture<>(); + + // when + stompSession.send(WEBSOCKET_PUB_URI, chatMessageTransDto); + stompSession.subscribe(WEBSOCKET_SUB_URI + chatMessageTransDto.getChatRoomId(), new StompFrameHandler() { + @Override + public Type getPayloadType(StompHeaders headers) { + return ChatMessageDto.ChatMessageTransDto.class; + } + + @Override + public void handleFrame(StompHeaders headers, Object payload) { + subscribeFuture.complete((ChatMessageDto.ChatMessageTransDto) payload); + } + }); + + // then + assertEquals(chatMessageTransDto.getContent(), subscribeFuture.get(10, TimeUnit.SECONDS).getContent()); + assertEquals(chatMessageTransDto.getContent(), chatMessageRepository.findAll().get(0).getContent()); + } +} \ No newline at end of file diff --git a/src/test/java/com/seniors/domain/chat/controller/ChatRoomControllerTest.java b/src/test/java/com/seniors/domain/chat/controller/ChatRoomControllerTest.java new file mode 100644 index 0000000..df7576a --- /dev/null +++ b/src/test/java/com/seniors/domain/chat/controller/ChatRoomControllerTest.java @@ -0,0 +1,189 @@ +package com.seniors.domain.chat.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.seniors.common.constant.OAuthProvider; +import com.seniors.common.constant.ResultCode; +import com.seniors.config.security.CustomUserDetails; +import com.seniors.domain.chat.dto.ChatRoomDto; +import com.seniors.domain.chat.entity.ChatRoom; +import com.seniors.domain.chat.entity.ChatRoomMembers; +import com.seniors.domain.chat.repository.ChatRoomMembersRepository; +import com.seniors.domain.chat.repository.ChatRoomRepository; +import com.seniors.domain.chat.service.ChatRoomService; +import com.seniors.domain.config.WithMockCustomUser; +import com.seniors.domain.users.entity.Users; +import com.seniors.domain.users.repository.UsersRepository; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +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.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +import java.util.Random; + +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@Transactional +@ActiveProfiles("dev") +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@SpringBootTest +@Slf4j +@WithMockCustomUser +class ChatRoomControllerTest { + + @Autowired + private ObjectMapper objectMapper; + @Autowired + private MockMvc mockMvc; + @Autowired + private ChatRoomService chatRoomService; + @Autowired + private ChatRoomRepository chatRoomRepository; + @Autowired + private UsersRepository usersRepository; + @Autowired + private ChatRoomMembersRepository chatRoomMembersRepository; + private Authentication authentication; + private Users users; + + @Autowired + private WebApplicationContext webApplicationContext; + + @BeforeEach + void setUp() { + + mockMvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .apply(springSecurity()) + .build(); + + authentication = SecurityContextHolder.getContext().getAuthentication(); + CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); + + users = usersRepository.getOneUsers(customUserDetails.getUserId()); + } + + @Test + @DisplayName("채팅방 전체 조회") + void chatRoomList() throws Exception { + + // given + Users users2 = Users.of("222", "test2@test2.com", "test2", OAuthProvider.KAKAO, + "male", "12-31", "20~29", "profileImageUrl"); + Users users3 = Users.of("333", "test3@test3.com", "test3", OAuthProvider.KAKAO, + "male", "10-31", "30~39", "profileImageUrl"); + try { + chatRoomService.addChatRoom(users.getId(), users2.getId()); + chatRoomService.addChatRoom(users.getId(), users3.getId()); + } catch (Exception e) { + } + + // expected + mockMvc.perform(get("/api/chat/rooms") + .contentType(APPLICATION_JSON) + .principal(authentication) + ) + .andExpect(status().isOk()) + .andDo(print()); + } + + @Test + @DisplayName("채팅방 생성") + void chatRoomAdd() throws Exception { + + // given + Users users2 = usersRepository.save(Users.of("222", "test2@test2.com", "test2", OAuthProvider.KAKAO, + "male", "12-31", "20~29", "profileImageUrl")); + + ChatRoomDto.ChatRoomCreateDto chatRoomCreateDto = new ChatRoomDto.ChatRoomCreateDto(); + chatRoomCreateDto.setChatUserId(users2.getId()); + String json = objectMapper.writeValueAsString(chatRoomCreateDto); + + // expected + mockMvc.perform(post("/api/chat/rooms") + .contentType(APPLICATION_JSON) + .content(json) + .principal(authentication) + ) + .andExpect(status().isOk()) + .andDo(print()); + } + @Test + @DisplayName("채팅방 생성 실패") + void failedChatRoomAdd() throws Exception { + + // given + Random random = new Random(); + long randomNumber = random.nextLong() % 100L; + if (randomNumber < 0) { + randomNumber *= -1; + } + + ChatRoomDto.ChatRoomCreateDto chatRoomCreateDto = new ChatRoomDto.ChatRoomCreateDto(); + chatRoomCreateDto.setChatUserId(randomNumber); + + String json = objectMapper.writeValueAsString(chatRoomCreateDto); + + // expected + mockMvc.perform(post("/api/chat/rooms") + .contentType(APPLICATION_JSON) + .content(json) + .principal(authentication) + ) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.code").value(ResultCode.NOT_FOUND.getCode())) + .andDo(print()); + } + + @Test + @DisplayName("채팅방 입장") + void chatRoomEnter() throws Exception { + + // given + ChatRoom chatRoom = new ChatRoom(); + chatRoomRepository.save(chatRoom); + chatRoomMembersRepository.save(ChatRoomMembers.of("user", chatRoom, users)); + + // expected + mockMvc.perform(get("/api/chat/rooms/{roomId}", chatRoom.getId()) + .contentType(APPLICATION_JSON) + .principal(authentication) + ).andExpect(status().isOk()) + .andDo(print()); + } + + @Test + @DisplayName("채팅방 나가기") + void chatRoomExit() throws Exception { + + // given + ChatRoom chatRoom = new ChatRoom(); + chatRoomRepository.save(chatRoom); + chatRoomMembersRepository.save(ChatRoomMembers.of("user", chatRoom, users)); + + // expected + mockMvc.perform(delete("/api/chat/rooms/{roomId}", chatRoom.getId()) + .contentType(APPLICATION_JSON) + .principal(authentication) + ).andExpect(status().isOk()) + .andDo(print()); + } +} \ No newline at end of file diff --git a/src/test/java/com/seniors/domain/chat/service/ChatMessageServiceTest.java b/src/test/java/com/seniors/domain/chat/service/ChatMessageServiceTest.java new file mode 100644 index 0000000..55a8520 --- /dev/null +++ b/src/test/java/com/seniors/domain/chat/service/ChatMessageServiceTest.java @@ -0,0 +1,87 @@ +package com.seniors.domain.chat.service; + +import com.seniors.config.security.CustomUserDetails; +import com.seniors.domain.chat.dto.ChatMessageDto; +import com.seniors.domain.chat.entity.ChatRoom; +import com.seniors.domain.chat.repository.ChatMessageRepository; +import com.seniors.domain.chat.repository.ChatRoomRepository; +import com.seniors.domain.config.WithMockCustomUser; +import com.seniors.domain.users.entity.Users; +import com.seniors.domain.users.repository.UsersRepository; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +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.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; + +@Transactional +@ActiveProfiles("dev") +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@EnableWebSocketMessageBroker +@Slf4j +@WithMockCustomUser + +class ChatMessageServiceTest { + + @Autowired + private ChatRoomRepository chatRoomRepository; + @Autowired + private MockMvc mockMvc; + @Autowired + private UsersRepository usersRepository; + @Autowired + private ChatMessageRepository chatMessageRepository; + private Authentication authentication; + @Autowired + private ChatMessageService chatMessageService; + private Users users; + + @Autowired + private WebApplicationContext webApplicationContext; + + + @BeforeEach + void setUp() { + + mockMvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .apply(springSecurity()) + .build(); + + authentication = SecurityContextHolder.getContext().getAuthentication(); + CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); + + users = usersRepository.getOneUsers(customUserDetails.getUserId()); + } + @Test + @DisplayName("채팅 메세지 저장") + public void saveChatMessage() { + // given + ChatRoom chatRoom = new ChatRoom(); + chatRoomRepository.save(chatRoom); + ChatMessageDto.ChatMessageTransDto chatMessageTransDto = ChatMessageDto.ChatMessageTransDto.of(chatRoom.getId(), users.getId(), "채팅 테스트입니다"); + + // when + ChatMessageDto.GetChatMessageListRes chatMessageListRes = chatMessageService.saveChatMessage(chatMessageTransDto); + + // then + assertEquals("채팅 테스트입니다", chatMessageRepository.findById(chatMessageListRes.getChatMessageId()).get().getContent()); + } +} \ No newline at end of file diff --git a/src/test/java/com/seniors/domain/chat/service/ChatRoomServiceTest.java b/src/test/java/com/seniors/domain/chat/service/ChatRoomServiceTest.java new file mode 100644 index 0000000..673c938 --- /dev/null +++ b/src/test/java/com/seniors/domain/chat/service/ChatRoomServiceTest.java @@ -0,0 +1,200 @@ +package com.seniors.domain.chat.service; + +import com.seniors.common.constant.OAuthProvider; +import com.seniors.config.security.CustomUserDetails; +import com.seniors.domain.chat.entity.ChatMessage; +import com.seniors.domain.chat.entity.ChatRoom; +import com.seniors.domain.chat.entity.ChatRoomMembers; +import com.seniors.domain.chat.repository.ChatMessageRepository; +import com.seniors.domain.chat.repository.ChatRoomMembersRepository; +import com.seniors.domain.chat.repository.ChatRoomRepository; +import com.seniors.domain.config.WithMockCustomUser; +import com.seniors.domain.users.entity.Users; +import com.seniors.domain.users.repository.UsersRepository; +import jakarta.persistence.EntityManager; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +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.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; + +@Transactional +@ActiveProfiles("dev") +@AutoConfigureMockMvc +@ExtendWith(SpringExtension.class) +@SpringBootTest +@Slf4j +@WithMockCustomUser +class ChatRoomServiceTest { + + @Autowired + private MockMvc mockMvc; + @Autowired + private ChatRoomService chatRoomService; + @Autowired + private ChatRoomRepository chatRoomRepository; + @Autowired + private UsersRepository usersRepository; + @Autowired + private ChatRoomMembersRepository chatRoomMembersRepository; + @Autowired + private ChatMessageRepository chatMessageRepository; + @Autowired + private EntityManager em; + private Authentication authentication; + private Users users; + + @Autowired + private WebApplicationContext webApplicationContext; + + @BeforeEach + void setUp() { + + mockMvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .apply(springSecurity()) + .build(); + + authentication = SecurityContextHolder.getContext().getAuthentication(); + CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); + + users = usersRepository.getOneUsers(customUserDetails.getUserId()); + } + + @Test + @DisplayName("채팅방 생성") + void addChatRoom() { + // given + Users users2 = usersRepository.save(Users.builder() + .snsId(String.valueOf(222)) + .email("test2@test2.com") + .nickname("user2") + .gender("male") + .ageRange("30~39") + .birthday("11-30") + .oAuthProvider(OAuthProvider.KAKAO) + .profileImageUrl("profileImageUrl") + .build()); + + // when + chatRoomService.addChatRoom(users.getId(), users2.getId());; + + // then + assertEquals(1L, chatRoomRepository.count()); + assertEquals(2L, chatRoomMembersRepository.count()); + } + + @Test + @DisplayName("채팅방 전체 조회") + void findChatRoom() { + // given + Users users2 = usersRepository.save(Users.builder() + .snsId(String.valueOf(222)) + .email("test2@test2.com") + .nickname("user2") + .gender("male") + .ageRange("30~39") + .birthday("11-30") + .oAuthProvider(OAuthProvider.KAKAO) + .profileImageUrl("profileImageUrl") + .build()); + + Users users3 = usersRepository.save(Users.builder() + .snsId(String.valueOf(333)) + .email("test3@test3.com") + .nickname("user3") + .gender("male") + .ageRange("40~49") + .birthday("10-30") + .oAuthProvider(OAuthProvider.KAKAO) + .profileImageUrl("profileImageUrl") + .build()); + + // when + ChatRoom chatRoom = chatRoomRepository.save(ChatRoom.builder().build()); + chatRoomMembersRepository.save(ChatRoomMembers.of(users.getNickname(), chatRoom, users)); + chatRoomMembersRepository.save(ChatRoomMembers.of(users2.getNickname(), chatRoom, users2)); + + ChatRoom chatRoom2 = chatRoomRepository.save(ChatRoom.builder().build()); + chatRoomMembersRepository.save(ChatRoomMembers.of(users.getNickname(), chatRoom2, users)); + chatRoomMembersRepository.save(ChatRoomMembers.of(users3.getNickname(), chatRoom2, users3)); + + chatMessageRepository.save(ChatMessage.of(chatRoom, users, "유저1입니다")); + chatMessageRepository.save(ChatMessage.of(chatRoom2, users, "유저1입니다")); + + // then + assertEquals(2, chatRoomService.findChatRoom(users.getId()).getChatRoomMembers().size()); + assertEquals(1, chatRoomService.findChatRoom(users2.getId()).getChatRoomMembers().size()); + assertEquals(1, chatRoomService.findChatRoom(users3.getId()).getChatRoomMembers().size()); + + } + + @Test + @DisplayName("채팅방 입장") + void findOneChatRoom() { + // given + Users users2 = usersRepository.save(Users.builder() + .snsId(String.valueOf(222)) + .email("test2@test2.com") + .nickname("user2") + .gender("male") + .ageRange("30~39") + .birthday("11-30") + .oAuthProvider(OAuthProvider.KAKAO) + .profileImageUrl("profileImageUrl") + .build()); + + // when + ChatRoom chatRoom = chatRoomRepository.save(ChatRoom.builder().build()); + chatRoomMembersRepository.save(ChatRoomMembers.of(users.getNickname(), chatRoom, users)); + chatRoomMembersRepository.save(ChatRoomMembers.of(users2.getNickname(), chatRoom, users2)); + + chatMessageRepository.save(ChatMessage.of(chatRoom, users, "채팅방1 입니다")); + + em.flush(); + em.clear(); + + // then + assertEquals("채팅방1 입니다", chatRoomService.findOneChatRoom(chatRoom.getId(), users.getId()).getChatMessages().get(0).getContent()); + + } + + @Test + @DisplayName("채팅방 삭제") + void removeChatRoom() { + // given + Users users2 = usersRepository.save(Users.builder() + .snsId(String.valueOf(222)) + .email("test2@test2.com") + .nickname("user2") + .gender("male") + .ageRange("30~39") + .birthday("11-30") + .oAuthProvider(OAuthProvider.KAKAO) + .profileImageUrl("profileImageUrl") + .build()); + + ChatRoom chatRoom = chatRoomRepository.save(ChatRoom.builder().build()); + chatRoomMembersRepository.save(ChatRoomMembers.of(users.getNickname(), chatRoom, users)); + + // when + chatRoomService.removeChatRoom(chatRoom.getId(), users.getId()); + + // then + assertEquals(0, chatRoomMembersRepository.count()); + } +} \ No newline at end of file diff --git a/src/test/java/com/seniors/domain/config/WithMockCustomUser.java b/src/test/java/com/seniors/domain/config/WithMockCustomUser.java new file mode 100644 index 0000000..64d9dc7 --- /dev/null +++ b/src/test/java/com/seniors/domain/config/WithMockCustomUser.java @@ -0,0 +1,22 @@ +package com.seniors.domain.config; + +import org.springframework.security.test.context.support.WithSecurityContext; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class) +public @interface WithMockCustomUser { + + long id() default 123456789L; + String snsId() default "snsId"; + String email() default "test@test.com"; + String nickName() default "TEST"; + String gender() default "male"; + String ageRange() default "20~29"; + String birthday() default "12-31"; + String profileImageUrl() default "profileImageUrl"; + String role() default "USER"; + +} diff --git a/src/test/java/com/seniors/domain/config/WithMockCustomUserSecurityContextFactory.java b/src/test/java/com/seniors/domain/config/WithMockCustomUserSecurityContextFactory.java new file mode 100644 index 0000000..a115a78 --- /dev/null +++ b/src/test/java/com/seniors/domain/config/WithMockCustomUserSecurityContextFactory.java @@ -0,0 +1,45 @@ +package com.seniors.domain.config; + +import com.seniors.common.constant.OAuthProvider; +import com.seniors.config.security.CustomUserDetails; +import com.seniors.domain.users.entity.Users; +import com.seniors.domain.users.repository.UsersRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.test.context.support.WithSecurityContextFactory; + +@RequiredArgsConstructor +public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory { + + private final UsersRepository usersRepository; + @Override + public SecurityContext createSecurityContext(WithMockCustomUser annotation) { + final SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + + Users users = usersRepository.save(Users.builder() + .snsId("123456789") + .email("test@test.com") + .nickname("test") + .gender("male") + .ageRange("20~29") + .birthday("12-31") + .oAuthProvider(OAuthProvider.KAKAO) + .build()); + CustomUserDetails userDetails = new CustomUserDetails( + users.getId(), + users.getSnsId(), + users.getEmail(), + users.getNickname(), + users.getGender(), + users.getProfileImageUrl()); + userDetails.setUserId(users.getId()); + + final UsernamePasswordAuthenticationToken authenticationToken + = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + + securityContext.setAuthentication(authenticationToken); + return securityContext; + } +}