-
Notifications
You must be signed in to change notification settings - Fork 3
feature : admin 기능 분리 및 UserDomainService 테스트코드 작성 #124
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
src/main/java/org/ezcode/codetest/application/usermanagement/user/service/AdminService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| package org.ezcode.codetest.application.usermanagement.user.service; | ||
|
|
||
| import org.ezcode.codetest.application.usermanagement.user.dto.response.GrantAdminRoleResponse; | ||
| import org.ezcode.codetest.domain.user.exception.AdminException; | ||
| import org.ezcode.codetest.domain.user.exception.code.AdminExceptionCode; | ||
| import org.ezcode.codetest.domain.user.model.entity.AuthUser; | ||
| import org.ezcode.codetest.domain.user.model.entity.User; | ||
| import org.ezcode.codetest.domain.user.model.enums.UserRole; | ||
| import org.ezcode.codetest.domain.user.service.UserDomainService; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class AdminService { | ||
| private final UserDomainService userDomainService; | ||
|
|
||
| @Transactional | ||
| public GrantAdminRoleResponse grantAdminRole(AuthUser authUser, Long userId) { | ||
| if (authUser.getId().equals(userId)) { | ||
| throw new AdminException(AdminExceptionCode.GRANT_ADMIN_SELF); | ||
| } | ||
| User user = userDomainService.getUserById(userId); | ||
| if (user.getRole().equals(UserRole.ADMIN)) { | ||
| throw new AdminException(AdminExceptionCode.ALREADY_ADMIN_USER); | ||
| } | ||
| user.modifyUserRole(UserRole.ADMIN); | ||
|
|
||
| return new GrantAdminRoleResponse("ADMIN 권한을 부여합니다"); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
src/main/java/org/ezcode/codetest/domain/user/exception/AdminException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package org.ezcode.codetest.domain.user.exception; | ||
|
|
||
| import org.ezcode.codetest.common.base.exception.ResponseCode; | ||
| import org.ezcode.codetest.domain.user.exception.code.AdminExceptionCode; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| import lombok.Getter; | ||
|
|
||
| @Getter | ||
| public class AdminException extends RuntimeException { | ||
| private final AdminExceptionCode responseCode; | ||
| private final HttpStatus httpStatus; | ||
| private final String message; | ||
|
|
||
| public AdminException(AdminExceptionCode responseCode) { | ||
| this.responseCode = responseCode; | ||
| this.httpStatus = responseCode.getStatus(); | ||
| this.message = responseCode.getMessage(); | ||
| } | ||
| } |
18 changes: 18 additions & 0 deletions
18
src/main/java/org/ezcode/codetest/domain/user/exception/code/AdminExceptionCode.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package org.ezcode.codetest.domain.user.exception.code; | ||
|
|
||
| import org.ezcode.codetest.common.base.exception.ResponseCode; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public enum AdminExceptionCode implements ResponseCode { | ||
| GRANT_ADMIN_SELF(false, HttpStatus.BAD_REQUEST, "본인에게 ADMIN 권한을 부여할 수 없습니다."), | ||
| ALREADY_ADMIN_USER(false, HttpStatus.BAD_REQUEST, "이미 ADMIN 권한을 가진 유저입니다."); | ||
|
|
||
| private final boolean success; | ||
| private final HttpStatus status; | ||
| private final String message; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
src/main/java/org/ezcode/codetest/presentation/usermanagement/AdminController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| package org.ezcode.codetest.presentation.usermanagement; | ||
|
|
||
| import org.ezcode.codetest.application.usermanagement.user.dto.response.GrantAdminRoleResponse; | ||
| import org.ezcode.codetest.application.usermanagement.user.service.AdminService; | ||
| import org.ezcode.codetest.domain.user.model.entity.AuthUser; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.security.core.annotation.AuthenticationPrincipal; | ||
| import org.springframework.web.bind.annotation.PathVariable; | ||
| import org.springframework.web.bind.annotation.PostMapping; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| import io.swagger.v3.oas.annotations.Operation; | ||
| import io.swagger.v3.oas.annotations.tags.Tag; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/api/admin") | ||
| @RequiredArgsConstructor | ||
| @Tag(name = "관리자(Admin) 전용 기능", description = "관리자 권한을 가진 유저만 접근 가능한 기능입니다") | ||
| public class AdminController { | ||
| private final AdminService adminService; | ||
|
|
||
| @Operation(summary = "관리자로 전환", description = "관리자 권한을 가지고 있는 유저는 다른 유저의 권한을 관리자로 수정할 수 있습니다.") | ||
| @PostMapping("/users/{userId}/grant-admin") | ||
| public ResponseEntity<GrantAdminRoleResponse> grantAdminRole( | ||
| @AuthenticationPrincipal AuthUser authUser, | ||
| @PathVariable Long userId | ||
| ){ | ||
| return ResponseEntity.status(HttpStatus.OK).body(adminService.grantAdminRole(authUser, userId)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
176 changes: 176 additions & 0 deletions
176
src/test/java/org/ezcode/codetest/domain/user/UserDomainServiceTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| package org.ezcode.codetest.domain.user; | ||
|
|
||
| import org.ezcode.codetest.common.security.util.PasswordEncoder; | ||
| import org.ezcode.codetest.domain.user.exception.AuthException; | ||
| import org.ezcode.codetest.domain.user.exception.UserException; | ||
| import org.ezcode.codetest.domain.user.exception.code.AuthExceptionCode; | ||
| import org.ezcode.codetest.domain.user.exception.code.UserExceptionCode; | ||
| import org.ezcode.codetest.domain.user.model.entity.User; | ||
| import org.ezcode.codetest.domain.user.model.entity.UserAuthType; | ||
| import org.ezcode.codetest.domain.user.model.enums.AuthType; | ||
| import org.ezcode.codetest.domain.user.model.enums.Tier; | ||
| import org.ezcode.codetest.domain.user.model.enums.UserRole; | ||
| import org.ezcode.codetest.domain.user.repository.UserAuthTypeRepository; | ||
| import org.ezcode.codetest.domain.user.repository.UserRepository; | ||
| import org.ezcode.codetest.domain.user.service.UserDomainService; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| 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 java.util.List; | ||
| import java.util.Optional; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.*; | ||
| import static org.mockito.ArgumentMatchers.any; | ||
| import static org.mockito.Mockito.*; | ||
|
|
||
| @ExtendWith(MockitoExtension.class) | ||
| public class UserDomainServiceTest { | ||
|
|
||
| @Mock | ||
| private UserRepository userRepository; | ||
|
|
||
| @Mock | ||
| private UserAuthTypeRepository userAuthTypeRepository; | ||
|
|
||
| @Mock | ||
| private PasswordEncoder passwordEncoder; | ||
|
|
||
|
|
||
| @InjectMocks | ||
| private UserDomainService userDomainService; | ||
|
|
||
| // 테스트 유저 정보 설정 | ||
| private final User testUser = new User( | ||
| "[email protected]", | ||
| "hashedPassword", | ||
| "testUser", | ||
| "TestNick", | ||
| 30, | ||
| Tier.NEWBIE, | ||
| UserRole.USER, | ||
| false, // isDeleted | ||
| true, // verified | ||
| "https://github.com/test", | ||
| false // gitPushStatus | ||
| ) { | ||
| public Long getId() { return 1L; } | ||
| public int getReviewToken() { return 5; } | ||
| public int getZeroReviewToken() { return 0; } | ||
| }; | ||
| private final UserAuthType testAuthType = new UserAuthType(testUser, AuthType.EMAIL); | ||
|
|
||
| // 1. 이메일 존재 여부 테스트 | ||
| @Test | ||
| void checkEmailUnique_shouldPassWhenEmailAvailable() { | ||
| when(userRepository.findByEmail("[email protected]")).thenReturn(Optional.empty()); | ||
| assertDoesNotThrow(() -> userDomainService.checkEmailUnique("[email protected]")); | ||
| } | ||
|
|
||
| @Test | ||
| void checkEmailUnique_shouldThrowWhenEmailExistsWithAuthType() { | ||
| when(userRepository.findByEmail("[email protected]")).thenReturn(Optional.of(testUser)); | ||
| when(userAuthTypeRepository.getUserAuthType(testUser)).thenReturn(List.of(AuthType.EMAIL)); | ||
|
|
||
| AuthException exception = assertThrows(AuthException.class, | ||
| () -> userDomainService.checkEmailUnique("[email protected]")); | ||
| assertEquals(AuthExceptionCode.ALREADY_EXIST_USER, exception.getResponseCode()); | ||
| } | ||
|
|
||
| // 2. 유저 생성 테스트 | ||
| @Test | ||
| void createUser_shouldCallRepository() { | ||
| userDomainService.createUser(testUser); | ||
| verify(userRepository).createUser(testUser); | ||
| } | ||
|
|
||
| @Test | ||
| void createUserAuthType_shouldCallRepository() { | ||
| userDomainService.createUserAuthType(testAuthType); | ||
| verify(userAuthTypeRepository).createUserAuthType(testAuthType); | ||
| } | ||
|
|
||
| // 3. 유저 존재 테스트 | ||
| @Test | ||
| void getUser_shouldReturnUserWhenExists() { | ||
| when(userRepository.findByEmail("[email protected]")).thenReturn(Optional.of(testUser)); | ||
| User result = userDomainService.getUser("[email protected]"); | ||
| assertEquals(testUser, result); | ||
| } | ||
|
|
||
| @Test | ||
| void getUser_shouldThrowWhenNotFound() { | ||
| when(userRepository.findByEmail("[email protected]")).thenReturn(Optional.empty()); | ||
| assertThrows(AuthException.class, () -> userDomainService.getUser("[email protected]")); | ||
| } | ||
|
|
||
| // 4. 비번 검증 테스트 | ||
| @Test | ||
| void userPasswordCheck_shouldPassWhenValid() { | ||
| when(userRepository.findByEmail("[email protected]")).thenReturn(Optional.of(testUser)); | ||
| when(passwordEncoder.matches("correct", "hashedPassword")).thenReturn(true); | ||
|
|
||
| assertDoesNotThrow(() -> | ||
| userDomainService.userPasswordCheck("[email protected]", "correct")); | ||
| } | ||
|
|
||
| @Test | ||
| void userPasswordCheck_shouldThrowWhenInvalid() { | ||
| when(passwordEncoder.matches(anyString(), anyString())).thenReturn(false); | ||
|
|
||
| when(userRepository.findByEmail("[email protected]")).thenReturn(Optional.of(testUser)); | ||
|
|
||
| AuthException exception = assertThrows(AuthException.class, | ||
| () -> userDomainService.userPasswordCheck("[email protected]", "wrong")); | ||
|
|
||
| assertEquals(AuthExceptionCode.PASSWORD_NOT_MATCH, exception.getResponseCode()); | ||
| } | ||
|
|
||
|
|
||
| // 5. 비번 인코딩 테스트 | ||
| @Test | ||
| void encodePassword_shouldReturnEncodedValue() { | ||
| when(passwordEncoder.encode("rawPassword")).thenReturn("encodedPassword"); | ||
| assertEquals("encodedPassword", userDomainService.encodePassword("rawPassword")); | ||
| } | ||
|
|
||
| // 6. 인증 타입 테스트 | ||
| @Test | ||
| void getUserAuthTypes_shouldReturnAuthTypes() { | ||
| List<AuthType> expectedTypes = List.of(AuthType.EMAIL, AuthType.GOOGLE); | ||
| when(userAuthTypeRepository.getUserAuthType(testUser)).thenReturn(expectedTypes); | ||
|
|
||
| assertEquals(expectedTypes, userDomainService.getUserAuthTypes(testUser)); | ||
| } | ||
|
|
||
| // 7. 비번 검증 테스트 | ||
| @Test | ||
| void passwordComparison_shouldThrowWhenSame() { | ||
| when(passwordEncoder.matches("newPass", "oldHashed")).thenReturn(true); | ||
| assertThrows(AuthException.class, | ||
| () -> userDomainService.passwordComparison("newPass", "oldHashed")); | ||
| } | ||
|
|
||
| @Test | ||
| void passwordComparison_shouldPassWhenDifferent() { | ||
| when(passwordEncoder.matches("newPass", "oldHashed")).thenReturn(false); | ||
| assertDoesNotThrow(() -> | ||
| userDomainService.passwordComparison("newPass", "oldHashed")); | ||
| } | ||
|
|
||
| // 8. 탈퇴 회원 테스트 | ||
| @Test | ||
| void isDeletedUser_shouldThrowWhenDeleted() { | ||
| User deletedUser = new User("[email protected]","Aa12345**", "username", | ||
| "[email protected]", 100, Tier.CODER, UserRole.USER, true, true, "gitUrl.com", true); | ||
| assertThrows(AuthException.class, () -> userDomainService.isDeletedUser(deletedUser)); | ||
| } | ||
|
|
||
| @Test | ||
| void isDeletedUser_shouldPassWhenActive() { | ||
| assertDoesNotThrow(() -> userDomainService.isDeletedUser(testUser)); | ||
| } | ||
|
|
||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
테스트 데이터 생성 방식의 일관성을 개선하세요.
익명 내부 클래스를 사용하여 테스트 유저를 생성하고 있는데, 이는 199-208라인의 zeroTokenUser와 일관성이 맞지 않습니다. 헬퍼 메서드를 사용하여 통일된 방식으로 테스트 데이터를 생성하는 것이 좋겠습니다.
다음과 같이 헬퍼 메서드를 추가하여 일관성을 개선하세요:
📝 Committable suggestion
🤖 Prompt for AI Agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
구차나..
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@minjee2758 네, 알겠습니다! 현재 테스트 코드 스타일을 유지하시는 것으로 하겠습니다. 테스트가 잘 작동하고 있으니 괜찮습니다. 🙂
🧠 Learnings used