Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: 가입시 인증 로직 테스트 코드 작성 #142

Merged
merged 1 commit into from
Sep 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.backend.connectable.acceptance;

import static org.assertj.core.api.Assertions.*;

import io.restassured.RestAssured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;

@ActiveProfiles("local")
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AuthAcceptanceTest {

private static final String 인증_요청_핸드폰_번호1 = "010-1234-1234";
private static final Long 인증_요청_유효_기간 = 1L;

@LocalServerPort public int port;

@BeforeEach
public void setUp() {
RestAssured.port = port;
}

@DisplayName("요청하여 응답받은 인증키를 이용하여 인증시 성공한다")
@Test
void successCertification() {
// given & when
String 응답받은_인증키 = 인증키를_요청한다();
Boolean 요청_성공_여부 = 인증키를_검증한다(응답받은_인증키);

// then
assertThat(요청_성공_여부).isTrue();
}

private static String 인증키를_요청한다() {
return RestAssured.given()
.log()
.all()
.contentType("text/plain")
.param("phoneNumber", 인증_요청_핸드폰_번호1)
.param("duration", 인증_요청_유효_기간)
.when()
.get("/auth/sms/key")
.then()
.log()
.all()
.extract()
.body()
.asString();
}

private static Boolean 인증키를_검증한다(String 인증키) {
return RestAssured.given()
.log()
.all()
.contentType("text/plain")
.param("phoneNumber", 인증_요청_핸드폰_번호1)
.param("authKey", 인증키)
.when()
.get("/auth/sms/certification")
.then()
.log()
.all()
.extract()
.response()
.as(Boolean.class);
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,63 @@
package com.backend.connectable.auth.service;

class AuthServiceTest {}
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;

import com.backend.connectable.exception.ConnectableException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class AuthServiceTest {

@Autowired private AuthService authService;

private final String phoneNumber = "010-2222-3333";
private final Long duration = 1L;

@DisplayName("인증키 획득 요청시 문자열 형태의 인증키를 반환받는다.")
@Test
void getAuthKey() {
// given & when
String authKey = authService.getAuthKey(phoneNumber, duration);

// then
assertThat(authKey).isNotBlank();
}

@DisplayName("발급받은 인증키로 인증 시 검증에 성공한다.")
@Test
void certifyKey() {
// give & when
String generatedKey = authService.getAuthKey(phoneNumber, duration);
Boolean isCertified = authService.certifyKey(phoneNumber, generatedKey);

// then
assertThat(isCertified).isTrue();
}

@DisplayName("서로 다른 요청에 의해 발급된 인증키는 같지 않아야 한다.")
@Test
void getAuthKeyDifference() {
// given & when
String generatedKey1 = authService.getAuthKey(phoneNumber, duration);
String generatedKey2 = authService.getAuthKey(phoneNumber, duration);

// then
assertThat(generatedKey1).isNotEqualTo(generatedKey2);
}

@DisplayName("인증에 실패시 false값을 예외처리에 의해 ConnectableException을 발생시킨다.")
@Test
void validateAuthKeyFail() {
// given & when
String generatedKey = authService.getAuthKey(phoneNumber, duration);
String authKey = "a1b2c3";

// then
assertThatThrownBy(() -> authService.certifyKey(generatedKey, authKey))
.isInstanceOf(ConnectableException.class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.backend.connectable.auth.ui;

import static org.mockito.BDDMockito.*;
import static org.springframework.http.MediaType.*;
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.*;

import com.backend.connectable.auth.service.AuthService;
import com.backend.connectable.security.JwtAuthenticationFilter;
import com.backend.connectable.security.SecurityConfiguration;
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.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.data.jpa.mapping.JpaMetamodelMappingContext;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;

@WebMvcTest(
controllers = AuthController.class,
excludeFilters = {
@ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE,
classes = {SecurityConfiguration.class, JwtAuthenticationFilter.class})
})
@MockBean(JpaMetamodelMappingContext.class)
class AuthControllerTest {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

컨트롤러 테스트 좋네요...! 응답을 간결하게 확인하기 좋아보입니다 굿


private static final String PHONE_NUMBER = "010-2222-3333";
private static final Long DURATION = 1L;
private static final String AUTH_KEY = "123123";

@Autowired private MockMvc mockMvc;

@MockBean private AuthService authService;

@DisplayName("비회원으로 인증키 요청시 문자열의 인증키를 받는데 성공한다.")
@WithMockUser
@Test
void getAuthKeySuccess() throws Exception {
// given & when
given(authService.getAuthKey(PHONE_NUMBER, DURATION)).willReturn(AUTH_KEY);

mockMvc.perform(
get(
"/auth/sms/key?phoneNumber={phone-number}&duration={duration}",
PHONE_NUMBER,
DURATION)
.contentType(APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(AUTH_KEY))
.andDo(print());
}

@DisplayName("비회원으로 인증키 검증 성공시 boolean=true를 반환받는다.")
@WithMockUser
@Test
void certifyAuthKeySuccess() throws Exception {
// given & when
boolean isCertified = true;
given(authService.certifyKey(PHONE_NUMBER, AUTH_KEY)).willReturn(isCertified);

// then
mockMvc.perform(
get(
"/auth/sms/certification?phoneNumber={phone-number}&authKey={authKey}",
PHONE_NUMBER,
AUTH_KEY)
.contentType(APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
}
}