Skip to content

Commit

Permalink
refactor: AuthenticationControllerTest 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
axhtl committed Sep 5, 2024
1 parent 4af2698 commit b2349a3
Show file tree
Hide file tree
Showing 5 changed files with 163 additions and 154 deletions.
2 changes: 2 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ dependencies {
testImplementation("io.kotest:kotest-runner-junit5:${kotestVersion}")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
testImplementation("com.squareup.okhttp3:okhttp:4.9.1")
testImplementation("com.squareup.okhttp3:mockwebserver:4.9.1")

//oauth2
implementation ("org.springframework.boot:spring-boot-starter-oauth2-client")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,9 @@ import org.store.clothstar.kakaoLogin.service.KakaoLoginService
class KakaoController(
private val kakaoLoginService: KakaoLoginService,
) {
// 인가코드 받기 - 액세스 토큰 받기 - 사용자 정보 받기
// 인가코드 받기
@GetMapping("/auth/kakao/callback")
fun kakaoCallback(@RequestParam code: String): ResponseEntity<String> {
// 액세스 토큰 받아오기 - 저장 나중에 하기
// val accessToken = kakaoLoginService.getAccessToken(code)
// // 사용자 정보 받아오기 - 저장 나중에 하기
// val userInfo = kakaoLoginService.getUserInfo(accessToken.accessToken!!)
// // 두 정보를 KakaoTokenUserInfoResponseDto로 합쳐서 반환
// val tokenUserInfo = TokenUserInfoResponseDto(
// accessToken = accessToken,
// userInfo = userInfo
// )
return ResponseEntity.ok(code)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
package org.store.clothstar.kakaoLogin.dto

import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty

class KakaoTokenResponseDto(s: String, accessToken: String, i: Int, s1: String, i1: Int) {
data class KakaoTokenResponseDto @JsonCreator constructor(

// 토큰 타입, bearer로 고정
@JsonProperty("token_type")
private val tokenType: String? = null
private val tokenType: String? = null,

// 사용자 액세스 토큰 값
@JsonProperty("access_token")
val accessToken: String? = null
val accessToken: String? = null,

// 액세스 토큰과 ID 토큰의 만료 시간(초)
@JsonProperty("expires_in")
private val expiresIn: Int? = null
private val expiresIn: Int? = null,

// 사용자 리프레시 토큰 값
@JsonProperty("refresh_token")
private val refreshToken: String? = null
private val refreshToken: String? = null,

// 리프레시 토큰 만료 시간(초)
@JsonProperty("refresh_token_expires_in")
private val refreshTokenExpiresIn: Int? = null
private val refreshTokenExpiresIn: Int? = null,

// 인증된 사용자의 정보 조회 권한 범위 / 범위가 여러 개일 경우, 공백으로 구분
@JsonProperty("scope")
private val scope: String? = null
}
private val scope: String? = null,
)
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ class KakaoLoginService {
private lateinit var redirectUri: String

@Value("\${spring.security.oauth2.client.provider.kakao.token_uri}")
private lateinit var tokenUri: String
lateinit var tokenUri: String

@Value("\${spring.security.oauth2.client.provider.kakao.user_info_uri}")
private lateinit var userUri: String
lateinit var userUri: String

// 토큰 가져오기
fun getAccessToken(code: String): KakaoTokenResponseDto {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,134 +1,148 @@
//package org.store.clothstar.member.authentication.controller
//
//import com.fasterxml.jackson.databind.ObjectMapper
//import org.junit.jupiter.api.DisplayName
//import org.junit.jupiter.api.Test
//import org.mockito.ArgumentMatchers.anyString
//import org.mockito.BDDMockito.given
//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.http.MediaType
//import org.springframework.test.context.ActiveProfiles
//import org.springframework.test.web.servlet.MockMvc
//import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
//import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
//import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
//import org.springframework.transaction.annotation.Transactional
//import org.store.clothstar.common.config.redis.RedisUtil
//import org.store.clothstar.kakaoLogin.dto.KakaoTokenResponseDto
//import org.store.clothstar.kakaoLogin.dto.KakaoUserInfoResponseDto
//import org.store.clothstar.kakaoLogin.service.KakaoLoginService
//import org.store.clothstar.kakaoLogin.vo.KakaoAccount
//import org.store.clothstar.member.authentication.domain.SignUpType
//import org.store.clothstar.member.dto.request.SignUpRequest
//import org.store.clothstar.member.util.CreateObject
//import kotlin.test.assertEquals
//
//@SpringBootTest
//@AutoConfigureMockMvc
//@ActiveProfiles("test")
//@Transactional
//class AuthenticationControllerTest(
// @Autowired private val mockMvc: MockMvc,
// @Autowired private val objectMapper: ObjectMapper,
// @Autowired private val redisUtil: RedisUtil,
//) {
// @MockBean
// private lateinit var kakaoLoginService: KakaoLoginService
//
// private val MEMBER_URL = "/v1/members"
// private val LOGIN_URL = "/v1/members/login"
//
// @DisplayName("멤버 일반 회원가입 통합테스트후 로그인 통합테스트")
// @Test
// fun normalSignUpIntegrationTest() {
// //given
// //이메일과 인증번호로 redis 데이터 생성
// val email = "[email protected]"
// val certifyNum = redisUtil.createdCertifyNum()
// redisUtil.createRedisData(email, certifyNum)
//
// // 이메일과 인증번호로 create DTO 객체 생성
// val createMemberRequest = CreateObject.getCreateMemberRequest(email, certifyNum)
// val signUpRequest = SignUpRequest(createMemberRequest, null)
// val requestBody = objectMapper.writeValueAsString(signUpRequest)
//
// // when
// val actions = mockMvc.perform(
// post(MEMBER_URL)
// .param("signUpType", SignUpType.NORMAL.toString())
// .contentType(MediaType.APPLICATION_JSON)
// .content(requestBody)
// )
//
// //then
// actions.andExpect(status().isCreated)
//
// //로그인 테스트
// //given
// val memberLoginRequest = CreateObject.getMemberLoginRequest()
// val loginRequestBody = objectMapper.writeValueAsString(memberLoginRequest)
//
// val loginActions = mockMvc.perform(
// post(LOGIN_URL)
// .contentType(MediaType.APPLICATION_JSON)
// .content(loginRequestBody)
// )
//
// loginActions.andExpect(status().isOk)
// }
//
// @DisplayName("멤버 카카오 회원가입 통합테스트")
// @Test
// fun kakaoSignUpIntegrationTest() {
// //given
// val name = "수빈"
// val telNo = "010-1231-0987"
// val code = "test_auth_code"
// val accessToken = "mock_access_token"
// val refreshToken = "mock_refresh_token"
// val email = "[email protected]"
//
// // KakaoLoginService가 반환할 Mock 데이터 설정
// val kakaoTokenResponseDto = KakaoTokenResponseDto("bearer", accessToken, 1000000, refreshToken, 3600)
// val kakaoUserInfoResponseDto = KakaoUserInfoResponseDto(
// id = 12345L,
// kakaoAccount = KakaoAccount(
// email = email,
// )
// )
//
// // KakaoLoginService의 getAccessToken, getUserInfo 메서드에 대해 mock 설정
// given(kakaoLoginService.getAccessToken(anyString())).willReturn(kakaoTokenResponseDto)
// given(kakaoLoginService.getUserInfo(anyString())).willReturn(kakaoUserInfoResponseDto)
//
// // when - 1: 카카오 콜백 호출
// val callbackActions = mockMvc.perform(
// get("/auth/kakao/callback")
// .param("code", code)
// )
//
//// assertEquals(code,"test_auth_code")
//
// // then - 1: 콜백 응답이 예상대로 이루어지는지 확인
// callbackActions.andExpect(status().isOk)
//
// // when - 2: 해당 인가 코드로 회원가입 요청
// val kakaoMemberRequest = CreateObject.getKakaoMemberRequest(name, telNo, code)
// val signUpRequest = SignUpRequest(null, kakaoMemberRequest)
// val requestBody = objectMapper.writeValueAsString(signUpRequest)
//
// //when
// val actions = mockMvc.perform(
// post(MEMBER_URL)
// .param("signUpType", SignUpType.KAKAO.toString())
// .contentType(MediaType.APPLICATION_JSON)
// .content(requestBody)
// )
//
// //then
// actions.andExpect(status().isCreated)
// }
//}
package org.store.clothstar.member.authentication.controller

import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.jupiter.api.DisplayName
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.transaction.annotation.Transactional
import org.store.clothstar.common.config.redis.RedisUtil
import org.store.clothstar.member.util.CreateObject
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.MediaType
import org.store.clothstar.kakaoLogin.service.KakaoLoginService
import org.store.clothstar.member.dto.request.KakaoMemberRequest
import org.store.clothstar.member.dto.request.SignUpRequest
import org.store.clothstar.member.authentication.domain.SignUpType

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Transactional
class AuthenticationControllerTest(
@Autowired private val mockMvc: MockMvc,
@Autowired private val objectMapper: ObjectMapper,
@Autowired private val redisUtil: RedisUtil,
@Autowired private val kakaoLoginService: KakaoLoginService,
) {
private val MEMBER_URL = "/v1/members"
private val LOGIN_URL = "/v1/members/login"

@DisplayName("멤버 일반 회원가입 통합테스트후 로그인 통합테스트")
@Test
fun normalSignUpIntegrationTest() {
//given
//이메일과 인증번호로 redis 데이터 생성
val email = "[email protected]"
val certifyNum = redisUtil.createdCertifyNum()
redisUtil.createRedisData(email, certifyNum)

// 이메일과 인증번호로 create DTO 객체 생성
val createMemberRequest = CreateObject.getCreateMemberRequest(email, certifyNum)
val signUpRequest = SignUpRequest(createMemberRequest, null)
val requestBody = objectMapper.writeValueAsString(signUpRequest)

// when
val actions = mockMvc.perform(
post(MEMBER_URL)
.param("signUpType", SignUpType.NORMAL.toString())
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody)
)

//then
actions.andExpect(status().isCreated)

//로그인 테스트
//given
val memberLoginRequest = CreateObject.getMemberLoginRequest()
val loginRequestBody = objectMapper.writeValueAsString(memberLoginRequest)

val loginActions = mockMvc.perform(
post(LOGIN_URL)
.contentType(MediaType.APPLICATION_JSON)
.content(loginRequestBody)
)

loginActions.andExpect(status().isOk)
}

@DisplayName("멤버 카카오 회원가입 통합테스트후 로그인 통합테스트")
@Test
fun kakaoSignUpIntegrationTest() {
val mockWebServer = MockWebServer()
mockWebServer.start()

//given
//KakaoLoginService의 tokenUri와 userUri를 MockWebServer로 설정
kakaoLoginService.tokenUri = mockWebServer.url("/token").toString()
kakaoLoginService.userUri = mockWebServer.url("/user").toString()

// 액세스 토큰 반환에 대한 응답 설정
val tokenResponse = """
{
"token_type": "bearer",
"access_token": "test_access_token",
"expires_in": 3600,
"refresh_token": "test_refresh_token",
"refresh_token_expires_in": 36000,
"scope": "account_email"
}
"""

//사용자 정보 반환에 대한 응답 설정
val userInfoResponse = """
{
"id": 123456789,
"kakao_account": {
"email": "[email protected]"
}
}
"""

//토큰 응답 추가(첫 번째 응답)
mockWebServer.enqueue(
MockResponse()
.setBody(tokenResponse)
.addHeader("Content-Type", "application/json")
)

//사용자 정보 응답 추가(두 번째 응답)
mockWebServer.enqueue(
MockResponse()
.setBody(userInfoResponse)
.addHeader("Content-Type", "application/json")
)

//요청 DTO 생성
val kakaoMemberRequest = KakaoMemberRequest(
name = "Test User",
telNo = "010-1234-5678",
email = null,
code = "test_code"
)

//requestBody 설정
val signUpRequest = SignUpRequest(null, kakaoMemberRequest)
val requestBody = objectMapper.writeValueAsString(signUpRequest)

//when
val actions = mockMvc.perform(
post(MEMBER_URL)
.param("signUpType", SignUpType.KAKAO.toString())
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody)
)

//then
actions.andExpect(status().isCreated)

mockWebServer.shutdown()
}
}

0 comments on commit b2349a3

Please sign in to comment.