From 842a7c78732b85c903a9b9e727e20efea543cce3 Mon Sep 17 00:00:00 2001 From: LSBsity Date: Sat, 3 Aug 2024 14:05:13 +0900 Subject: [PATCH] remove: test --- .../doghae/common/BaseRepositoryTest.java | 23 -- .../controller/ControllerTestSetup.java | 43 ---- .../common/controller/WithCustomUser.java | 16 -- .../WithCustomUserSecurityContextFactory.java | 25 -- .../doghae/common/testdata/TestAuth.java | 10 - .../doghae/common/testdata/TestUser.java | 28 --- .../oauth/controller/AuthControllerTest.java | 105 -------- .../oauth/service/KakaoOAuthServiceTest.java | 229 ------------------ 8 files changed, 479 deletions(-) delete mode 100644 src/test/java/team5/doghae/common/BaseRepositoryTest.java delete mode 100644 src/test/java/team5/doghae/common/controller/ControllerTestSetup.java delete mode 100644 src/test/java/team5/doghae/common/controller/WithCustomUser.java delete mode 100644 src/test/java/team5/doghae/common/controller/WithCustomUserSecurityContextFactory.java delete mode 100644 src/test/java/team5/doghae/common/testdata/TestAuth.java delete mode 100644 src/test/java/team5/doghae/common/testdata/TestUser.java delete mode 100644 src/test/java/team5/doghae/domain/oauth/controller/AuthControllerTest.java delete mode 100644 src/test/java/team5/doghae/domain/oauth/service/KakaoOAuthServiceTest.java diff --git a/src/test/java/team5/doghae/common/BaseRepositoryTest.java b/src/test/java/team5/doghae/common/BaseRepositoryTest.java deleted file mode 100644 index ba30905..0000000 --- a/src/test/java/team5/doghae/common/BaseRepositoryTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package team5.doghae.common; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import team5.doghae.common.testdata.TestUser; -import team5.doghae.domain.user.domain.User; -import team5.doghae.domain.user.repository.UserRepository; - - -@DataJpaTest -@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) -public abstract class BaseRepositoryTest { - - - @Autowired - protected UserRepository userRepository; - - protected User createUser() { - return userRepository.save(TestUser.createUser()); - } - -} diff --git a/src/test/java/team5/doghae/common/controller/ControllerTestSetup.java b/src/test/java/team5/doghae/common/controller/ControllerTestSetup.java deleted file mode 100644 index 73cd396..0000000 --- a/src/test/java/team5/doghae/common/controller/ControllerTestSetup.java +++ /dev/null @@ -1,43 +0,0 @@ -package team5.doghae.common.controller; - -import org.junit.jupiter.api.BeforeEach; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.context.annotation.Import; -import org.springframework.data.jpa.mapping.JpaMetamodelMappingContext; -import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.result.MockMvcResultHandlers; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import team5.doghae.domain.validator.CustomCollectionValidator; - -import java.time.LocalDateTime; - -@Import({CustomCollectionValidator.class}) -@MockBean(JpaMetamodelMappingContext.class) -public class ControllerTestSetup { - - protected static final long REQUEST_USER_ID = 1L; - protected MockMvc mockMvc; - protected MockMvc noSecurityMockMvc; - - // "yyyy-MM-dd'T'HH:mm" 형식으로 변환 - protected static String parseLocalDateTime(LocalDateTime input) { - String inputString = input.toString(); - if (inputString.length() <= 18) { - return inputString; - } - return inputString.substring(0, 18); - } - - @BeforeEach - void setUp(WebApplicationContext context) { - this.mockMvc = MockMvcBuilders.webAppContextSetup(context) - .apply(SecurityMockMvcConfigurers.springSecurity()) - .alwaysDo(MockMvcResultHandlers.print()) - .build(); - this.noSecurityMockMvc = MockMvcBuilders.webAppContextSetup(context) - .alwaysDo(MockMvcResultHandlers.print()) - .build(); - } -} diff --git a/src/test/java/team5/doghae/common/controller/WithCustomUser.java b/src/test/java/team5/doghae/common/controller/WithCustomUser.java deleted file mode 100644 index 6bddd54..0000000 --- a/src/test/java/team5/doghae/common/controller/WithCustomUser.java +++ /dev/null @@ -1,16 +0,0 @@ -package team5.doghae.common.controller; - -import org.springframework.security.test.context.support.WithSecurityContext; -import team5.doghae.domain.user.domain.UserRole; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(RetentionPolicy.RUNTIME) -@WithSecurityContext(factory = WithCustomUserSecurityContextFactory.class) -public @interface WithCustomUser { - long userId() default 1L; - - UserRole userRole() default UserRole.USER; - -} diff --git a/src/test/java/team5/doghae/common/controller/WithCustomUserSecurityContextFactory.java b/src/test/java/team5/doghae/common/controller/WithCustomUserSecurityContextFactory.java deleted file mode 100644 index b7b96be..0000000 --- a/src/test/java/team5/doghae/common/controller/WithCustomUserSecurityContextFactory.java +++ /dev/null @@ -1,25 +0,0 @@ -package team5.doghae.common.controller; - -import io.jsonwebtoken.impl.DefaultClaims; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.test.context.support.WithSecurityContextFactory; -import team5.doghae.common.security.jwt.JwtAuthenticationToken; -import team5.doghae.common.security.jwt.JwtProperties; - -public class WithCustomUserSecurityContextFactory implements WithSecurityContextFactory { - - @Override - public SecurityContext createSecurityContext(WithCustomUser customUser) { - - DefaultClaims claims = new DefaultClaims(); - claims.put(JwtProperties.USER_ID, customUser.userId()); - claims.put(JwtProperties.USER_ROLE, customUser.userRole().getKey()); - - JwtAuthenticationToken authentication = new JwtAuthenticationToken(claims, "", null); - SecurityContext context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(authentication); - - return context; - } -} \ No newline at end of file diff --git a/src/test/java/team5/doghae/common/testdata/TestAuth.java b/src/test/java/team5/doghae/common/testdata/TestAuth.java deleted file mode 100644 index 88e10d8..0000000 --- a/src/test/java/team5/doghae/common/testdata/TestAuth.java +++ /dev/null @@ -1,10 +0,0 @@ -package team5.doghae.common.testdata; - -import team5.doghae.domain.oauth.domain.Auth; -import team5.doghae.domain.user.domain.User; - -public class TestAuth { - public static Auth createAuth(User user) { - return Auth.create(user, "refreshToken"); - } -} diff --git a/src/test/java/team5/doghae/common/testdata/TestUser.java b/src/test/java/team5/doghae/common/testdata/TestUser.java deleted file mode 100644 index 8ebd376..0000000 --- a/src/test/java/team5/doghae/common/testdata/TestUser.java +++ /dev/null @@ -1,28 +0,0 @@ -package team5.doghae.common.testdata; - -import org.springframework.test.util.ReflectionTestUtils; -import team5.doghae.domain.user.domain.SocialCode; -import team5.doghae.domain.user.domain.User; -import team5.doghae.domain.user.domain.UserRole; - -public class TestUser { - public static User createUser() { - return User.create("email@gmail.com", SocialCode.KAKAO); - } - - public static User createUserWithId(Long userId) { - User user = createUser(); - ReflectionTestUtils.setField(user, "id", userId); - return user; - } - - public static User createAdminUserWithId(Long userId) { - User user = createUserWithId(userId); - ReflectionTestUtils.setField(user, "userRole", UserRole.ADMIN); - return user; - } - - public static User createUserWithSocialCode(SocialCode socialCode) { - return User.create("email@gmail.com", socialCode); - } -} diff --git a/src/test/java/team5/doghae/domain/oauth/controller/AuthControllerTest.java b/src/test/java/team5/doghae/domain/oauth/controller/AuthControllerTest.java deleted file mode 100644 index ff89158..0000000 --- a/src/test/java/team5/doghae/domain/oauth/controller/AuthControllerTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package team5.doghae.domain.oauth.controller; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; -import org.springframework.test.web.servlet.ResultActions; -import team5.doghae.common.controller.ControllerTestSetup; -import team5.doghae.common.controller.WithCustomUser; -import team5.doghae.common.security.jwt.JwtProvider; -import team5.doghae.domain.oauth.dto.ResponseJwtToken; -import team5.doghae.domain.oauth.service.KakaoOAuthService; -import team5.doghae.domain.oauth.service.OAuthService; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; -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.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - - -@WebMvcTest(AuthController.class) -class AuthControllerTest extends ControllerTestSetup { - - private final String BASIC_URL = "/oauth2"; - - @MockBean - private OAuthService oAuthService; - @MockBean - private KakaoOAuthService kakaoOAuthService; - @MockBean - private JwtProvider jwtProvider; - - @Nested - @DisplayName("kakao 메서드는") - class KakaoLoginTest { - - @Test - @DisplayName("정상 흐름이면 access token과 refresh token을 발급한다.") - void return_access_token_and_refresh_token() throws Exception { - //given - String authCode = "authCode"; - String jwtAccessToken = "jwtAccessToken"; - String jwtRefreshToken = "jwtRefreshToken"; - given(kakaoOAuthService.login(any(String.class))) - .willReturn(ResponseJwtToken.of(jwtAccessToken, jwtRefreshToken)); - - //when - ResultActions result = noSecurityMockMvc.perform(get(BASIC_URL + "/kakao/login?code=" + authCode) - .with(SecurityMockMvcRequestPostProcessors.csrf())); - - //then - result.andExpect(status().isOk()) - .andExpect(header().string("Authorization", jwtAccessToken)) - .andExpect(cookie().value("refreshToken", jwtRefreshToken)); - } - } - - @Nested - @DisplayName("getAccessToken 메서드는") - class GetAccessTokenTest { - - @Test - @DisplayName("정상 흐름이면 access token을 발급한다.") - void return_access_token() throws Exception { - //given - String jwtAccessToken = "jwtAccessToken"; - given(jwtProvider.createNewAccessTokenFromRefreshToken(any(String.class))) - .willReturn(jwtAccessToken); - - //when - ResultActions result = noSecurityMockMvc.perform(get(BASIC_URL + "/refresh") - .header("Authorization", "Bearer " + "refreshToken")); - - //then - - result.andExpect(status().isOk()) - .andExpect(header().string("Authorization", jwtAccessToken)); - verify(jwtProvider).validRefreshToken(any(String.class)); - } - } - - @Nested - @WithCustomUser - @DisplayName("deleteAccount 메서드는") - class DeleteAccountTest { - - @Test - @DisplayName("정상 흐름이면 계정을 삭제하고 204를 반환한다.") - void delete_account() throws Exception { - //given - //when - ResultActions result = mockMvc.perform(delete(BASIC_URL + "/users") - .with(SecurityMockMvcRequestPostProcessors.csrf())); - - //then - result.andExpect(status().isNoContent()); - verify(oAuthService).deleteAccount(any(Long.class)); - } - } -} diff --git a/src/test/java/team5/doghae/domain/oauth/service/KakaoOAuthServiceTest.java b/src/test/java/team5/doghae/domain/oauth/service/KakaoOAuthServiceTest.java deleted file mode 100644 index dcc4344..0000000 --- a/src/test/java/team5/doghae/domain/oauth/service/KakaoOAuthServiceTest.java +++ /dev/null @@ -1,229 +0,0 @@ -package team5.doghae.domain.oauth.service; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; -import team5.doghae.common.exception.BusinessException; -import team5.doghae.common.security.jwt.JwtProvider; -import team5.doghae.common.testdata.TestAuth; -import team5.doghae.domain.oauth.dto.*; -import team5.doghae.domain.oauth.properties.KakaoProperties; -import team5.doghae.domain.oauth.repository.AuthRepository; -import team5.doghae.domain.user.domain.SocialCode; -import team5.doghae.domain.user.domain.User; -import team5.doghae.domain.user.service.UserService; -import team5.doghae.domain.user.service.ValidateUserService; - -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static team5.doghae.common.testdata.TestUser.*; -import static team5.doghae.common.testdata.TestUser.createUserWithId; - -@ExtendWith(MockitoExtension.class) -class KakaoOAuthServiceTest { - - @Mock - private KakaoProperties kakaoProperties; - @Mock - private RestTemplate restTemplate; - @Mock - private ObjectMapper objectMapper; - @Mock - private UserService userService; - @Mock - private ValidateUserService validateUserService; - @Mock - private AuthRepository authRepository; - @Mock - private JwtProvider jwtTokenProvider; - @InjectMocks - private KakaoOAuthService kakaoOauthService; - - @Nested - @DisplayName("login 메소드 테스트") - class Login_test { - - @Nested - @DisplayName("REST 요청으로 받은") - class Rest_request { - - @BeforeEach - void setUp() { - given(kakaoProperties.getApiKey()).willReturn("apiKey"); - given(kakaoProperties.getSecretKey()).willReturn("clientSecret"); - given(kakaoProperties.getRedirectUri()).willReturn("redirectUri"); - given(kakaoProperties.getTokenUrl()).willReturn("tokenUrl"); - } - - @Test - @DisplayName("유저 프로필을 파싱하는데 실패할 경우 오류를 반환한다.") - void user_profile_parsing_fail_then_return_error() throws Exception { - // given - given(restTemplate.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class), any(Class.class))) - .willReturn(ResponseEntity.of(Optional.of("json body"))); - given(objectMapper.readValue(any(String.class), eq(OAuthAccessToken.class))) - .willThrow(JsonProcessingException.class); - // when - // then - assertThatThrownBy(() -> kakaoOauthService.login("test")) - .isInstanceOf(BusinessException.class); - } - } - - @Nested - @DisplayName("유저 이메일을 알아낸 뒤") - class After_find_user_email { - - @BeforeEach - void setUp() throws Exception { - given(kakaoProperties.getUserInfoUrl()) - .willReturn("userInfoUrl"); - given(kakaoProperties.getTokenUrl()) - .willReturn("tokenUrl"); - given(objectMapper.readValue(any(String.class), any(Class.class))) - .willReturn(new OAuthAccessToken("token", "token", "Bearer", 360000, 360000, "scope")); - given(restTemplate.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class), any(Class.class))) - .willReturn(ResponseEntity.of(Optional.of("json body"))); - given(objectMapper.readValue(any(String.class), eq(KakaoOAuthUserProfile.class))) - .willReturn(new KakaoOAuthUserProfile(new KakaoAccount("email"))); - } - - @Test - @DisplayName("유저가 존재하지 않을 경우 회원가입을 진행하고 토큰을 반환한다.") - void user_not_exist_then_register_and_return_token() { - // given - User newUser = createUserWithId(1L); - String accessToken = "accessToken"; - String refreshToken = "refreshToken"; - - given(validateUserService.validateRegisteredUserByEmail(any(String.class), eq(SocialCode.KAKAO))) - .willReturn(null); - given(userService.registerWithOAuth(any(String.class), eq(SocialCode.KAKAO), any(String.class))) - .willReturn(newUser); - given(jwtTokenProvider.createAccessToken(eq(newUser.getId()), eq(newUser.getUserRole()))) - .willReturn(accessToken); - given(jwtTokenProvider.createRefreshToken(eq(newUser.getId()), eq(newUser.getUserRole()))) - .willReturn(refreshToken); - - // when - ResponseJwtToken responseJwtToken = kakaoOauthService.login("test"); - - // then - verify(userService).registerWithOAuth(any(String.class), eq(SocialCode.KAKAO), any(String.class)); - assertThat(responseJwtToken.getRefreshToken()).isEqualTo(refreshToken); - assertThat(responseJwtToken.getAccessToken()).isEqualTo(accessToken); - } - - @Test - @DisplayName("유저가 존재할 경우 회원가입을 진행하지 않고 토큰을 반환한다.") - void user_exist_then_no_register() { - // given - User user = createUserWithId(1L); - String accessToken = "accessToken"; - String refreshToken = "refreshToken"; - - given(validateUserService.validateRegisteredUserByEmail(any(String.class), eq(SocialCode.KAKAO))) - .willReturn(user); - given(jwtTokenProvider.createAccessToken(eq(user.getId()), eq(user.getUserRole()))) - .willReturn(accessToken); - given(jwtTokenProvider.createRefreshToken(eq(user.getId()), eq(user.getUserRole()))) - .willReturn(refreshToken); - - // when - ResponseJwtToken responseJwtToken = kakaoOauthService.login("test"); - - // then - verify(userService, never()).registerWithOAuth(any(String.class), eq(SocialCode.KAKAO), any(String.class)); - assertThat(responseJwtToken.getAccessToken()).isEqualTo(accessToken); - assertThat(responseJwtToken.getRefreshToken()).isEqualTo(refreshToken); - } - } - } - - @Nested - @DisplayName("deleteAccount 메서드 테스트") - class DeleteAccount_Test { - - @Test - @DisplayName("유저 아이디에 해당하는 Auth가 없을 경우 회원탈퇴를 진행하지 않는다.") - void no_auth_then_no_delete() { - //given - User user = createUser(); - given(authRepository.findByUser(eq(user))) - .willReturn(Optional.empty()); - - //when - //then - assertThatThrownBy(() -> kakaoOauthService.deleteAccount(user)) - .isInstanceOf(BusinessException.class); - verify(restTemplate, never()).postForObject(any(String.class), any(HttpEntity.class), - any(Class.class)); - assertThat(user.getDeletedAt()).isNull(); - } - - - @Nested - @DisplayName("유저 아이디에 해당하는 Auth가 있을 경우") - class Exist_auth { - - @Test - @DisplayName("회원탈퇴를 진행한다.") - void exist_auth_then_delete_user() { - //given - User user = createUser(); - given(authRepository.findByUser(eq(user))) - .willReturn(Optional.of(TestAuth.createAuth(user))); - given(kakaoProperties.getDeleteAccountUrl()) - .willReturn("deleteAccountUrl"); - given(restTemplate.postForObject(any(String.class), any(HttpEntity.class), - eq(String.class))).willReturn(""); - - //when - kakaoOauthService.deleteAccount(user); - - //then - assertThat(user.getDeletedAt()).isNotNull(); - } - - @Test - @DisplayName("회원탈퇴 REST 요청이 실패하면 예외를 던진다.") - void rest_request_fail_then_throw_exception() { - //given - User user = createUser(); - given(authRepository.findByUser(eq(user))).willReturn(Optional.of( - TestAuth.createAuth(user))); - given(kakaoProperties.getDeleteAccountUrl()) - .willReturn("deleteAccountUrl"); - given(restTemplate.postForObject(any(String.class), any(HttpEntity.class), - eq(String.class))) - .willReturn("{\"error\":\"invalid_token\",\"error_description\":\"Invalid Value\"}"); - - //when - //then - assertThatThrownBy(() -> kakaoOauthService.deleteAccount(user)) - .isInstanceOf(BusinessException.class); - assertThat(user.getDeletedAt()).isNull(); - } - } - } -} - -