Skip to content

Commit

Permalink
test: restTemplate 및 서비스 테스트 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
parksey committed Nov 2, 2023
1 parent 95bea5d commit 7e53464
Show file tree
Hide file tree
Showing 9 changed files with 207 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ private String generateQueryParamsWith(AuthorizationCodeRequest authorizationCod
return authorizationCodeUri.toUriString();
}

private void validAuthorizationGrant(AuthorizationCodeResponse authorizationCodeResponse) {
if (authorizationCodeResponse.code() == null) {
private void validAuthorizationGrant(String code) {
if (code == null) {
throw new BadRequestException(ErrorMessage.GRANT_FAILED);
}
}
Expand Down Expand Up @@ -85,7 +85,7 @@ public void redirectToLoginPage(HttpServletResponse httpServletResponse) {
}

public void requestToken(AuthorizationCodeResponse authorizationCodeResponse) {
validAuthorizationGrant(authorizationCodeResponse);
validAuthorizationGrant(authorizationCodeResponse.code());
issueTokenToAuthorizationServer(authorizationCodeResponse.code());
// TODO 발급한 토큰으로 사용자의 정보 얻어와야함 : 프로필 & 닉네임
}
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/com/moabam/api/domain/entity/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -89,18 +89,22 @@ private Member(Long id, String socialId, String nickname, String profileImage, B
}

public void enterMorningRoom() {
this.currentMorningCount++;
currentMorningCount++;
}

public void enterNightRoom() {
this.currentNightCount++;
currentNightCount++;
}

public void exitMorningRoom() {
this.currentMorningCount--;
if (currentMorningCount > 0) {
currentMorningCount--;
}
}

public void exitNightRoom() {
this.currentNightCount--;
if (currentMorningCount > 0) {
currentNightCount--;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.moabam.api.presentation;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

Expand All @@ -23,7 +24,7 @@ public void socialLogin(HttpServletResponse httpServletResponse) {
}

@GetMapping("/login/kakao/oauth")
public void authorizationTokenIssue(AuthorizationCodeResponse authorizationCodeResponse) {
public void authorizationTokenIssue(@ModelAttribute AuthorizationCodeResponse authorizationCodeResponse) {
authenticationService.requestToken(authorizationCodeResponse);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,17 @@
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.util.ReflectionTestUtils;

import com.moabam.api.dto.AuthorizationCodeRequest;
import com.moabam.api.dto.AuthorizationCodeResponse;
import com.moabam.api.dto.AuthorizationTokenRequest;
import com.moabam.api.dto.AuthorizationTokenResponse;
import com.moabam.api.dto.OAuthMapper;
import com.moabam.fixture.AuthorizationTokenResponseFixture;
import com.moabam.global.config.OAuthConfig;
import com.moabam.global.error.exception.BadRequestException;
import com.moabam.global.error.model.ErrorMessage;
Expand Down Expand Up @@ -90,9 +95,9 @@ void redirect_loginPage_success() {
verify(oAuth2AuthorizationServerRequestService).loginRequest(eq(mockHttpServletResponse), anyString());
}

@DisplayName("인가코드 반환 실패 테스트")
@DisplayName("인가코드 반환 실패")
@Test
void authorization_grant_fail_test() {
void authorization_grant_fail() {
// Given
AuthorizationCodeResponse authorizationCodeResponse = new AuthorizationCodeResponse(null, "error",
"errorDescription", null);
Expand All @@ -102,4 +107,54 @@ void authorization_grant_fail_test() {
.isInstanceOf(BadRequestException.class)
.hasMessage(ErrorMessage.GRANT_FAILED.getMessage());
}

@DisplayName("인가코드 반환 성공")
@Test
void authorization_grant_success() {
// Given
AuthorizationCodeResponse authorizationCodeResponse = new AuthorizationCodeResponse("test", null,
null, null);
AuthorizationTokenResponse authorizationTokenResponse =
AuthorizationTokenResponseFixture.authorizationTokenResponse();

// When
when(oAuth2AuthorizationServerRequestService.requestAuthorizationServer(anyString(), any())).thenReturn(
new ResponseEntity<>(authorizationTokenResponse, HttpStatus.OK));

// When + Then
assertThatNoException().isThrownBy(() -> authenticationService.requestToken(authorizationCodeResponse));
}

@DisplayName("토큰 요청 매퍼 실패 - code null")
@Test
void token_request_mapping_failBy_code() {
// When + Then
Assertions.assertThatThrownBy(() -> OAuthMapper.toAuthorizationTokenRequest(oauthConfig, null))
.isInstanceOf(NullPointerException.class);
}

@DisplayName("토큰 요청 매퍼 실패 - config 에러")
@Test
void token_request_mapping_failBy_config() {
// When + Then
Assertions.assertThatThrownBy(() -> OAuthMapper.toAuthorizationTokenRequest(noOAuthConfig, "Test"))
.isInstanceOf(NullPointerException.class);
}

@DisplayName("토큰 요청 매퍼 성공")
@Test
void token_request_mapping_success() {
// Given
String code = "Test";
AuthorizationTokenRequest authorizationTokenRequest = OAuthMapper.toAuthorizationTokenRequest(oauthConfig,
code);

// When + Then
assertThat(authorizationTokenRequest).isNotNull();
assertAll(
() -> assertThat(authorizationTokenRequest.clientId()).isEqualTo(oauthConfig.client().clientId()),
() -> assertThat(authorizationTokenRequest.redirectUri()).isEqualTo(oauthConfig.provider().redirectUri()),
() -> assertThat(authorizationTokenRequest.code()).isEqualTo(code)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class LoginPage {
@Test
void authorization_code_uri_generate_success() throws IOException {
// given
MockHttpServletResponse mockHttpServletResponse = mockHttpServletResponse = new MockHttpServletResponse();
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

// when
oAuth2AuthorizationServerRequestService.loginRequest(mockHttpServletResponse, uri);
Expand Down
40 changes: 40 additions & 0 deletions src/test/java/com/moabam/api/domain/entity/MemberTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import com.moabam.api.domain.entity.enums.Role;
import com.moabam.fixture.MemberFixture;
import com.moabam.global.common.util.BaseImageUrl;

class MemberTest {
Expand Down Expand Up @@ -70,4 +72,42 @@ void create_member_failBy_nickname() {
.socialId(socialId)::build)
.isInstanceOf(NullPointerException.class);
}

@DisplayName("멤버 방 출입 기능 테스트")
@Nested
class MemberRoomInOut {

@DisplayName("회원 방 입장 성공")
@Test
void member_room_enter_success() {
// given
Member member = MemberFixture.member();

// when
int beforeMorningCount = member.getCurrentMorningCount();
member.enterMorningRoom();

int beforeNightCount = member.getCurrentNightCount();
member.enterNightRoom();

// then
assertThat(member.getCurrentMorningCount()).isEqualTo(beforeMorningCount + 1);
assertThat(member.getCurrentMorningCount()).isEqualTo(beforeNightCount + 1);
}

@DisplayName("회원 방 탈출 성공")
@Test
void member_room_exit_success() {
// given
Member member = MemberFixture.member();

// when
member.exitMorningRoom();
member.exitNightRoom();

// then
assertThat(member.getCurrentMorningCount()).isZero();
assertThat(member.getCurrentMorningCount()).isZero();
}
}
}
89 changes: 74 additions & 15 deletions src/test/java/com/moabam/api/presentation/MemberControllerTest.java
Original file line number Diff line number Diff line change
@@ -1,34 +1,50 @@
package com.moabam.api.presentation;

import static com.moabam.global.common.util.OAuthParameterNames.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static com.moabam.global.common.util.OAuthParameterNames.CLIENT_ID;
import static com.moabam.global.common.util.OAuthParameterNames.CLIENT_SECRET;
import static com.moabam.global.common.util.OAuthParameterNames.CODE;
import static com.moabam.global.common.util.OAuthParameterNames.GRANT_TYPE;
import static com.moabam.global.common.util.OAuthParameterNames.REDIRECT_URI;
import static com.moabam.global.common.util.OAuthParameterNames.RESPONSE_TYPE;
import static com.moabam.global.common.util.OAuthParameterNames.SCOPE;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.BeforeAll;
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.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.match.MockRestRequestMatchers;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.moabam.api.application.AuthenticationService;
import com.moabam.api.application.OAuth2AuthorizationServerRequestService;
import com.moabam.api.dto.AuthorizationCodeResponse;
import com.moabam.fixture.AuthorizationTokenResponseFixture;
import com.moabam.global.common.util.GlobalConstant;
import com.moabam.global.config.OAuthConfig;

@SpringBootTest(
properties = {
"oauth2.provider.authorization-uri=https://kauth.kakao.com/oauth/authorize",
"oauth2.provider.redirect-uri=http://localhost:8080/members/login/kakao/oauth",
"oauth2.client.client-id=testtesttesttesttesttesttesttesttest",
"oauth2.client.authorization-grant-type=authorization_code",
"oauth2.client.scope=profile_nickname,profile_image"
}
)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class MemberControllerTest {

@Autowired
Expand All @@ -38,11 +54,27 @@ class MemberControllerTest {
ObjectMapper objectMapper;

@Autowired
AuthenticationService authenticationService;
OAuth2AuthorizationServerRequestService oAuth2AuthorizationServerRequestService;

@Autowired
OAuthConfig oAuthConfig;

static RestTemplate restTemplate;

MockRestServiceServer mockRestServiceServer;

@BeforeAll
static void allSetUp() {
restTemplate = new RestTemplate();
}

@BeforeEach
void setUp() {
// TODO 추후 RestTemplate -> REstTemplateBuilder & Bean등록하여 테스트 코드도 일부 변경됨
ReflectionTestUtils.setField(oAuth2AuthorizationServerRequestService, "restTemplate", restTemplate);
mockRestServiceServer = MockRestServiceServer.createServer(restTemplate);
}

@DisplayName("인가 코드 받기 위한 로그인 페이지 요청")
@Test
void authorization_code_request_success() throws Exception {
Expand All @@ -61,6 +93,33 @@ void authorization_code_request_success() throws Exception {
result.andExpect(status().is3xxRedirection())
.andExpect(header().string("Content-type",
MediaType.APPLICATION_FORM_URLENCODED_VALUE + GlobalConstant.CHARSET_UTF_8))
.andExpect(redirectedUrl(uri));
.andExpect(MockMvcResultMatchers.redirectedUrl(uri));
}

@DisplayName("Authorization Server에 토큰 발급 요청")
@Test
void authorization_token_request_success() throws Exception {
// given
MultiValueMap<String, String> contentParams = new LinkedMultiValueMap<>();
contentParams.add(GRANT_TYPE, oAuthConfig.client().authorizationGrantType());
contentParams.add(CLIENT_ID, oAuthConfig.client().clientId());
contentParams.add(REDIRECT_URI, oAuthConfig.provider().redirectUri());
contentParams.add(CODE, "test");
contentParams.add(CLIENT_SECRET, oAuthConfig.client().clientSecret());

String response = objectMapper.writeValueAsString(
AuthorizationTokenResponseFixture.authorizationTokenResponse());
AuthorizationCodeResponse authorizationCodeResponse = new AuthorizationCodeResponse("test", null, null, null);

mockRestServiceServer.expect(requestTo(oAuthConfig.provider().tokenUri()))
.andExpect(MockRestRequestMatchers.content().formData(contentParams))
.andExpect(MockRestRequestMatchers.content().contentType("application/x-www-form-urlencoded;charset=UTF-8"))
.andExpect(method(HttpMethod.POST))
.andRespond(withSuccess(response, MediaType.APPLICATION_JSON));

// expected
ResultActions result = mockMvc.perform(get("/members/login/kakao/oauth")
.flashAttr("authorizationCodeResponse", authorizationCodeResponse))
.andExpect(status().isOk());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.moabam.fixture;

import com.moabam.api.dto.AuthorizationTokenResponse;

public class AuthorizationTokenResponseFixture {

static final String tokenType = "tokenType";
static final String accessToken = "accessToken";
static final String idToken = "id";
static final String expiresin = "exp";
static final String refreshToken = "ref";
static final String refreshTokenExpiresIn = "refs";
static final String scope = "scope";

public static AuthorizationTokenResponse authorizationTokenResponse() {
return new AuthorizationTokenResponse(tokenType, accessToken, idToken,
expiresin, refreshToken, refreshTokenExpiresIn, scope);
}
}
6 changes: 3 additions & 3 deletions src/test/resources/application-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ oauth2:
- profile_image

provider:
authorization_uri: https://test.com/test/test
redirect_uri: http://test:8080/test
token_uri: https://test.test.com/test/test
authorization_uri: https://authorization.com/test/test
redirect_uri: http://redirect:8080/test
token_uri: https://token.com/test/test

0 comments on commit 7e53464

Please sign in to comment.