Skip to content

Conversation

@nahowo
Copy link
Contributor

@nahowo nahowo commented May 7, 2025

Summary

Description

  • User Controller 중복 제거
  • User Service 메서드 분리
  • User Controller/Service 테스트 코드 추가

Screenshot

Test Checklist

  • 체크리스트

Summary by CodeRabbit

  • 버그 수정
    • 사용자명 중복 확인 응답이 항상 "중복 아님" 코드로 반환되던 문제를 수정하였습니다. 실제 중복 여부는 응답의 데이터(boolean)로 확인할 수 있습니다.
  • 스타일
    • 일부 코드의 가독성을 높이기 위해 포맷팅을 개선하였습니다.
  • 리팩터링
    • 사용자 생성 및 중복 확인 로직이 모듈화되어 유지보수성과 가독성이 향상되었습니다.
  • 테스트
    • 사용자명 중복 확인 및 사용자 생성/수정에 대한 단위 테스트가 추가 및 개선되었습니다.

@nahowo nahowo self-assigned this May 7, 2025
@nahowo nahowo linked an issue May 7, 2025 that may be closed by this pull request
@coderabbitai
Copy link

coderabbitai bot commented May 7, 2025

"""

Walkthrough

사용자 생성 및 중복 검사 로직이 서비스 계층에서 모듈화되어, 검증, 저장, 토큰 발급 기능이 분리되었습니다. 컨트롤러의 사용자명 중복 검사 응답이 단순화되었고, 관련 단위 테스트가 새롭게 작성 및 리팩토링되었습니다. DTO의 코드 스타일이 개선되었습니다.

Changes

파일/경로 변경 요약
src/main/java/com/Alchive/backend/controller/UserController.java isDuplicateUsername 메서드의 반환 로직 단순화, 항상 동일 코드와 중복 여부 반환
src/main/java/com/Alchive/backend/dto/response/UserResponseDTO.java 생성자 내 대입 연산자 주변 공백 추가(코드 스타일 개선)
src/main/java/com/Alchive/backend/service/UserService.java createUser 메서드 리팩토링: 검증, 저장, 토큰 발급 분리. isDuplicatedUsername 공개 메서드화, createUserTokens 추가
src/test/java/com/Alchive/backend/controller/UserControllerTest.java UserController의 사용자명 중복 검사 단위 테스트 신규 작성
src/test/java/com/Alchive/backend/service/UserServiceTest.java UserServiceTest 전체 리팩토링: 생성, 중복, 수정 관련 테스트만 남기고 나머지 제거

Sequence Diagram(s)

sequenceDiagram
    participant Controller as UserController
    participant Service as UserService
    participant Repo as UserRepository
    participant Token as JwtTokenProvider
    participant Refresh as RefreshTokenService

    Controller->>Service: createUser(request)
    Service->>Service: isDuplicatedEmailUsername(request)
    Service->>Repo: existsByEmail(request.email)
    Service->>Repo: existsByName(request.name)
    Service->>Service: createSaveUser(request)
    Service->>Repo: save(user)
    Service->>Service: createUserTokens(user.email)
    Service->>Token: createAccessToken(user.email)
    Service->>Token: createRefreshToken(user.email)
    Service->>Refresh: save(refreshToken)
    Service-->>Controller: UserResponseDTO(user, accessToken)
Loading

Suggested reviewers

  • dlwhsk0

Poem

🐇
코드를 깔끔하게, 테스트도 새로,
중복 검사는 한결같이 바로!
서비스 분리로 역할을 나누니
토끼도 기뻐 깡총깡총 뛰지요.
스타일도 예쁘게,
우리 팀 모두 힘내요!
🥕
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 04eaf9f and 38dd325.

📒 Files selected for processing (1)
  • src/test/java/com/Alchive/backend/controller/UserControllerTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/test/java/com/Alchive/backend/controller/UserControllerTest.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🔭 Outside diff range comments (1)
src/test/java/com/Alchive/backend/controller/UserControllerTest.java (1)

1-45: 🛠️ Refactor suggestion

테스트 메서드 이름과 실제 동작이 일치하지 않습니다.

테스트 메서드 이름과 기대 동작 사이에 불일치가 있습니다:

  • isDuplicateUsernameSuccess는 중복된 유저네임을 테스트하는데 "성공"이라고 명명되었습니다
  • isDuplicateUsernameFail는 중복되지 않은 유저네임을 테스트하는데 "실패"라고 명명되었습니다

이는 직관에 반하여 혼란을 줄 수 있습니다.

메서드 이름을 다음과 같이 변경하세요:

-@DisplayName("UserController 유저네임 중복 - 성공")
+@DisplayName("UserController 유저네임 중복 확인 - 중복된 경우")
 @Test
-public void isDuplicateUsernameSuccess() {
+public void isDuplicateUsername_WhenDuplicated() {
     when(userService.isDuplicatedUsername("testNameUnique")).thenReturn(true);

     ResponseEntity<ResultResponse> result = sut.isDuplicateUsername("testNameUnique");

     Assertions.assertEquals(true, result.getBody().getData());
 }
-@DisplayName("UserController 유저네임 중복 - 실패")
+@DisplayName("UserController 유저네임 중복 확인 - 중복되지 않은 경우")
 @Test
-public void isDuplicateUsernameFail() {
+public void isDuplicateUsername_WhenNotDuplicated() {
     when(userService.isDuplicatedUsername("testNameDuplicated")).thenReturn(false);

     ResponseEntity<ResultResponse> result = sut.isDuplicateUsername("testNameDuplicated");

     Assertions.assertEquals(false, result.getBody().getData());
 }
🧹 Nitpick comments (2)
src/test/java/com/Alchive/backend/controller/UserControllerTest.java (1)

24-25: 빈 setUp 메서드는 필요한가요?

현재 setUp 메서드가 비어 있습니다. 필요하지 않다면 제거하는 것이 좋습니다.

src/test/java/com/Alchive/backend/service/UserServiceTest.java (1)

81-92: 유저 정보 수정 테스트가 필요한 내용을 검증합니다.

사용자 세부 정보 업데이트 테스트가 적절히 구현되었습니다. 하지만 다른 필드도 업데이트할 수 있다면 추가 검증이 필요할 수 있습니다.

다른 업데이트 가능한 필드(예: 프로필 이미지, 비밀번호 등)가 있다면 추가 테스트 케이스를 작성하는 것을 고려해보세요. 또한 업데이트 실패 케이스(예: 사용자를 찾을 수 없는 경우)에 대한 테스트도 유용할 수 있습니다.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7b28b11 and 04eaf9f.

📒 Files selected for processing (5)
  • src/main/java/com/Alchive/backend/controller/UserController.java (1 hunks)
  • src/main/java/com/Alchive/backend/dto/response/UserResponseDTO.java (1 hunks)
  • src/main/java/com/Alchive/backend/service/UserService.java (1 hunks)
  • src/test/java/com/Alchive/backend/controller/UserControllerTest.java (1 hunks)
  • src/test/java/com/Alchive/backend/service/UserServiceTest.java (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/test/java/com/Alchive/backend/controller/UserControllerTest.java (1)
src/test/java/com/Alchive/backend/service/UserServiceTest.java (1)
  • ExtendWith (27-93)
src/test/java/com/Alchive/backend/service/UserServiceTest.java (1)
src/test/java/com/Alchive/backend/controller/UserControllerTest.java (1)
  • ExtendWith (17-44)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (12)
src/main/java/com/Alchive/backend/dto/response/UserResponseDTO.java (1)

16-19: 코드 스타일 개선이 적용되었습니다.

대입 연산자 주변에 공백을 추가하여 가독성이 향상되었습니다.

src/main/java/com/Alchive/backend/controller/UserController.java (1)

37-37: 컨트롤러 로직이 적절하게 단순화되었습니다.

이전 코드에서는 조건부 로직이 있었을 것으로 추정되는데, 이제 서비스 계층에 중복 검사 로직을 위임하고 컨트롤러는 결과만 반환하는 형태로 개선되었습니다. 이는 단일 책임 원칙(SRP)에 더 잘 부합합니다.

src/main/java/com/Alchive/backend/service/UserService.java (5)

27-37: 메서드 분리를 통한 가독성 및 재사용성 향상

createUser 메서드가 더 작고 집중된 메서드들로 잘 분리되었습니다. 이는 단일 책임 원칙(SRP)을 따르며, 코드의 가독성과 테스트 용이성을 향상시킵니다.


39-46: 명확한 책임 분리

이메일과 사용자명 중복 검사를 별도의 메서드로 분리하여 코드 가독성이 향상되었습니다. 예외 처리도 명확하게 이루어지고 있습니다.


48-54: 중복 검사 메서드의 적절한 분리

이메일과 사용자명 중복 검사를 별도의 메서드로 분리하고, 사용자명 중복 검사 메서드를 public으로 노출한 것은 좋은 결정입니다. 이를 통해 컨트롤러에서 직접 호출할 수 있게 되었습니다.


56-59: 사용자 생성 및 저장 책임 분리

사용자 생성과 저장 로직을 별도의 메서드로 분리하여 코드 가독성이 향상되었습니다.


61-66: 토큰 생성 로직의 적절한 분리

토큰 생성 로직을 별도의 메서드로 분리하여 재사용성과 가독성이 향상되었습니다. 액세스 토큰과 리프레시 토큰을 함께 처리하는 메서드가 잘 구성되었습니다.

src/test/java/com/Alchive/backend/service/UserServiceTest.java (5)

1-37: 테스트 클래스 기본 구성이 개선되었습니다.

클래스 구조가 더 명확해졌고 Mockito 확장 사용과 필요한 의존성 모킹이 잘 설정되었습니다. 특히 이전 코드에서 TokenServiceHttpServletRequest 모킹 대신 JwtTokenProviderRefreshTokenService를 모킹하는 방식으로 변경된 것이 서비스 계층 리팩토링에 적절히 대응하고 있습니다.


38-43: 테스트 데이터 설정이 간결해졌습니다.

공통 테스트 데이터를 멤버 변수로 정의하여 코드 중복을 줄이고 가독성을 높였습니다. 특히 User 객체를 직접 생성하는 방식으로 단순화한 점이 좋습니다.


44-60: 유저 생성 성공 테스트가 잘 구현되었습니다.

Service 계층 리팩토링에 맞춰 토큰 생성과 중복 체크, 유저 저장 등의 모든 로직을 포함하고 있습니다. 특히 refreshToken 저장 로직 테스트를 위한 doNothing() 사용이 적절합니다.


62-69: 이메일 중복 예외 처리 테스트가 간결하게 작성되었습니다.

UserEmailExistException 예외 발생을 검증하는 테스트가 잘 구현되었습니다.


71-79: 유저네임 중복 예외 처리 테스트가 명확하게 작성되었습니다.

UserNameExistException 예외 발생을 검증하는 테스트가 잘 구현되었습니다.

@nahowo nahowo merged commit d11492a into develop May 7, 2025
2 checks passed
@nahowo nahowo deleted the refactor/#103 branch May 7, 2025 07:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[refactor] User 로직 리팩토링

2 participants