Skip to content
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
Expand Up @@ -3,15 +3,22 @@
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.example.gimmegonghakauth.dao.MajorsDao;
import com.example.gimmegonghakauth.dao.UserDao;
import com.example.gimmegonghakauth.domain.MajorsDomain;
import com.example.gimmegonghakauth.domain.UserDomain;
import jakarta.transaction.Transactional;
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.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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
Expand All @@ -24,13 +31,31 @@
@Nested
@DisplayName("유저 컨트롤러 테스트")
@ActiveProfiles("test")
@Transactional
//@TestPropertySource(locations = "classpath:submodule-properties/application-test.properties")
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@Transactional
@Autowired
private UserDao userDao;

@Autowired
private MajorsDao majorsDao;

@BeforeEach
public void setUser() {
String encodedPassword = new BCryptPasswordEncoder().encode("qwer");

UserDomain user = UserDomain.builder().studentId(19111111L)
.password(encodedPassword).email("test@sju.com")
.majorsDomain(majorsDao.findByMajor("컴퓨터공학과"))
.name("testUser")
.build();
userDao.save(user);
}

@Test
@DisplayName("회원가입시 비밀번호 일치 테스트 (일치)")
public void testSignupWithMatchingPasswords() throws Exception {
Expand All @@ -51,7 +76,7 @@ public void testSignupWithMatchingPasswords() throws Exception {
@DisplayName("회원가입시 비밀번호 일치 테스트 (불일치)")
void testSignupWithMisMatchedPasswords() throws Exception {
mockMvc.perform(post("/user//signup")
.param("studentId", "19111111")
.param("studentId", "19654321")
.param("password1", "password123")
.param("password2", "mismatchedPassword")
.param("email", "test@example.com")
Expand Down Expand Up @@ -83,8 +108,7 @@ void testDuplicatedStudentId() throws Exception {
// 가정2: studentId 에서 "duplicate" 오류
}

@Transactional
@Test //(주의) DB 내용기반으로 테스트됨
@Test
@DisplayName("회원 탈퇴시 비밀번호 일치 테스트 (일치)")
@WithMockUser(username = "19111111", password = "qwer", roles = "USER")
public void testWithdrawalWithValidPassword() throws Exception {
Expand All @@ -95,7 +119,6 @@ public void testWithdrawalWithValidPassword() throws Exception {
.andExpect(redirectedUrl("/user/logout"));
}

@Transactional
@Test //(주의) DB 내용기반으로 테스트됨
@DisplayName("회원 탈퇴시 비밀번호 일치 테스트 (불일치)")
@WithMockUser(username = "19111111", password = "qwer", roles = "USER")
Expand All @@ -110,7 +133,6 @@ public void testWithdrawalWithInvalidPassword() throws Exception {
//가정2 : 탈퇴가 실패하면 withdrawalError 에러 발생
}

@Transactional
@Test
@DisplayName("비밀번호 변경 성공")
@WithMockUser(username = "19111111", password = "qwer", roles = "USER")
Expand All @@ -124,7 +146,6 @@ public void testChangePasswordSuccess() throws Exception {
.andExpect(redirectedUrl("/user/login"));
}

@Transactional
@Test
@DisplayName("비밀번호 변경 실패(현재 비밀번호 불일치)")
@WithMockUser(username = "19111111", password = "qwer", roles = "USER")
Expand All @@ -136,12 +157,12 @@ public void testChangePasswordFail1() throws Exception {
.with(csrf()))
.andExpect(MockMvcResultMatchers.view().name("user/changePassword"))
.andExpect(MockMvcResultMatchers.model()
.attributeHasFieldErrorCode("changePasswordDto", "currentPassword", "currentPasswordInCorrect"));
.attributeHasFieldErrorCode("changePasswordDto", "currentPassword",
"currentPasswordInCorrect"));
//가정1 : 변경이 실패하면 비밀번호 변경 폼으로 이동
//가정2 : 변경이 실패하면 currentPasswordInCorrect 에러 발생
}

@Transactional
@Test
@DisplayName("비밀번호 변경 실패 (새 비밀번호와 현재 비밀번호와 일치)")
@WithMockUser(username = "19111111", password = "qwer", roles = "USER")
Expand All @@ -153,12 +174,12 @@ public void testChangePasswordFail2() throws Exception {
.with(csrf()))
.andExpect(MockMvcResultMatchers.view().name("user/changePassword"))
.andExpect(MockMvcResultMatchers.model()
.attributeHasFieldErrorCode("changePasswordDto", "newPassword1", "sameCurrentPassword"));
.attributeHasFieldErrorCode("changePasswordDto", "newPassword1",
"sameCurrentPassword"));
//가정1 : 변경이 실패하면 비밀번호 변경 폼으로 이동
//가정2 : 변경이 실패하면 currentPasswordInCorrect 에러 발생
}

@Transactional
@Test
@DisplayName("비밀번호 변경 실패(새 비밀번호 재입력 불일치)")
@WithMockUser(username = "19111111", password = "qwer", roles = "USER")
Expand All @@ -170,7 +191,8 @@ public void testChangePasswordFail3() throws Exception {
.with(csrf()))
.andExpect(MockMvcResultMatchers.view().name("user/changePassword"))
.andExpect(MockMvcResultMatchers.model()
.attributeHasFieldErrorCode("changePasswordDto", "newPassword2", "newPasswordInCorrect"));
.attributeHasFieldErrorCode("changePasswordDto", "newPassword2",
"newPasswordInCorrect"));
//가정1 : 변경이 실패하면 비밀번호 변경 폼으로 이동
//가정2 : 변경이 실패하면 currentPasswordInCorrect 에러 발생
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ public void setCourses() {
@BeforeEach
public void setUser() {
//유저 Entity save
UserDomain user = UserDomain.builder().studentId(19011684L)
.password("1234").email("test@gmail.com")
UserDomain user = UserDomain.builder().studentId(19111111L)
.password("qwer").email("test@gmail.com")
.majorsDomain(majorsDao.findByMajor("컴퓨터공학과"))
.name("이희수")
.name("testUser")
.build();
userDao.save(user);
}
Expand All @@ -85,15 +85,15 @@ public void testUploadFile() {
//기이수 과목 데이터1
CompletedCoursesDomain data1 =
CompletedCoursesDomain.builder().
userDomain(userDao.findByStudentId(19011684L).get()).
userDomain(userDao.findByStudentId(19111111L).get()).
Copy link
Contributor

Choose a reason for hiding this comment

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

19111111 학번은 해당 테스트 코드에서만 사용되는 학번인건가요??

Copy link
Contributor Author

@gmltn9233 gmltn9233 Sep 10, 2024

Choose a reason for hiding this comment

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

넵 해당 테스트 코드가 실행될때 해당 학번을 가진 유저가 생성되고 종료되면 삭제됩니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

아하 클래스 레벨에 @Transactional 덕분에 나중에 롤백되는건가요?

Copy link
Contributor Author

@gmltn9233 gmltn9233 Sep 10, 2024

Choose a reason for hiding this comment

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

아하 클래스 레벨에 @Transactional 덕분에 나중에 롤백되는건가요?

그렇습니다. 이전에 InitData에 Test에 필요한 DB 데이터를 미리 입력해 놓았다면, 리팩토링 후 @Transactional 을 통해 테스트 코드마다 필요한 데이터를 테스트 레벨에서만 존재하도록 수정하였습니다!

Copy link
Contributor

Choose a reason for hiding this comment

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

오오 그러면 굳이 별도의 test DB를 쓰지 않아도 되겠네요! 테스트 방법 배워갑니다~ ㅎㅎ

coursesDomain(coursesDao.findByCourseId(12345L)).
year(23).semester("1학기").
build();

//기이수 과목 데이터2
CompletedCoursesDomain data2 =
CompletedCoursesDomain.builder().
userDomain(userDao.findByStudentId(19011684L).get()).
userDomain(userDao.findByStudentId(19111111L).get()).
coursesDomain(coursesDao.findByCourseId(54321L)).
year(23).semester("1학기").
build();
Expand All @@ -107,14 +107,14 @@ public void testUploadFile() {
dataList.add(data1);
dataList.add(data2);

UserDomain user = userDao.findByStudentId(19011684L).get();
UserDomain user = userDao.findByStudentId(19111111L).get();
assertEquals(dataList, completedCoursesDao.findByUserDomain(user));
}

@Test
@DisplayName("재업로드 테스트1(첫 업로드)")
public void testUserUploadStatus1() {
UserDomain user = userDao.findByStudentId(19011684L).get();
UserDomain user = userDao.findByStudentId(19111111L).get();

//데이터 확인
completedCoursesService.checkUser(user);
Expand All @@ -132,7 +132,7 @@ public void testUserUploadStatus2() {
//기이수 과목 데이터 1
CompletedCoursesDomain data1 =
CompletedCoursesDomain.builder().
userDomain(userDao.findByStudentId(19011684L).get()).
userDomain(userDao.findByStudentId(19111111L).get()).
coursesDomain(coursesDao.findByCourseId(12345L)).
year(23).semester("1학기").
build();
Expand All @@ -142,7 +142,7 @@ public void testUserUploadStatus2() {
List<CompletedCoursesDomain> dataList = new ArrayList<>();
dataList.add(data1);

UserDomain user = userDao.findByStudentId(19011684L).get();
UserDomain user = userDao.findByStudentId(19111111L).get();

//데이터 삭제
completedCoursesService.checkUser(user);
Expand All @@ -160,14 +160,14 @@ public void testUserUploadStatus3() {
//기이수 과목 데이터 1
CompletedCoursesDomain data1 =
CompletedCoursesDomain.builder().
userDomain(userDao.findByStudentId(19011684L).get()).
userDomain(userDao.findByStudentId(19111111L).get()).
coursesDomain(coursesDao.findByCourseId(12345L)).
year(23).semester("1학기").
build();
//기이수 과목 데이터 2
CompletedCoursesDomain data2 =
CompletedCoursesDomain.builder().
userDomain(userDao.findByStudentId(19011684L).get()).
userDomain(userDao.findByStudentId(19111111L).get()).
coursesDomain(coursesDao.findByCourseId(12345L)).
year(23).semester("1학기").
build();
Expand All @@ -179,7 +179,7 @@ public void testUserUploadStatus3() {
dataList.add(data1);
dataList.add(data2);

UserDomain user = userDao.findByStudentId(19011684L).get();
UserDomain user = userDao.findByStudentId(19111111L).get();

//데이터 삭제
completedCoursesService.checkUser(user);
Expand Down
Loading