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: 스터디 수료 쿠폰 관련 테스트 추가 #870

Merged
merged 8 commits into from
Feb 9, 2025

Conversation

Sangwook02
Copy link
Member

@Sangwook02 Sangwook02 commented Feb 8, 2025

🌱 관련 이슈

📌 작업 내용 및 특이사항

  • 스터디 수료처리/철회시 발생하는 issuedCoupon 발급/회수 로직 test 추가했습니다.
  • join시 fetchJoin이 없으면 lazyinitializationexception이 발생해서 fetchJoin 추가했습니다.

📝 참고사항

📚 기타

Summary by CodeRabbit

  • Tests
    • 스터디 완료 쿠폰 발급 시, 쿠폰 생성과 중복 발급 방지를 검증하는 테스트 케이스를 추가하였습니다.
    • 스터디 완료 쿠폰 회수 시, 쿠폰 상태 업데이트가 올바르게 이루어지는지 확인하는 테스트 케이스를 추가하였습니다.

@Sangwook02 Sangwook02 self-assigned this Feb 8, 2025
@Sangwook02 Sangwook02 requested a review from a team as a code owner February 8, 2025 06:22
Copy link

coderabbitai bot commented Feb 8, 2025

Caution

Review failed

The pull request is closed.

"""

Walkthrough

이번 PR은 CouponServiceTest 클래스에 새로운 nested 테스트 클래스와 메소드를 추가하여 스터디 수료 쿠폰의 발급과 회수 검증을 진행합니다. 두 개의 새로운 클래스(스터디_수료_쿠폰_발급시, 스터디_수료_쿠폰_회수시) 내에서 쿠폰 생성, 중복 확인, 신규 생성 및 회수 기능을 테스트하는 메소드가 추가되었으며, 관련 import 문도 함께 도입되었습니다.

Changes

파일 변경 요약
src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponServiceTest.java 스터디 수료 쿠폰 발급과 회수를 위한 새로운 nested 클래스(스터디_수료_쿠폰_발급시, 스터디_수료_쿠폰_회수시)와 관련 테스트 메소드 추가, 관련 import 추가

Assessment against linked issues

Objective Addressed Explanation
스터디 수료 쿠폰 관련 테스트 추가 (#842)

Possibly related PRs

Suggested labels

✨ feature

Suggested reviewers

  • kckc0608
  • uwoobeat

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 2a95f10 and e55ba0a.

📒 Files selected for processing (1)
  • src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponServiceTest.java (2 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.

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. (Beta)
  • @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

github-actions bot commented Feb 8, 2025

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

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: 0

🧹 Nitpick comments (1)
src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponEventHandlerTest.java (1)

103-131: 수료 철회 이벤트에 대한 테스트도 잘 작성되었습니다!

쿠폰 회수 로직이 정상적으로 동작하는지 확인하는 테스트가 잘 구현되어 있습니다. 다만, 다음과 같은 추가 테스트 케이스도 고려해 보시면 좋을 것 같습니다:

  • 이미 회수된 쿠폰에 대한 중복 회수 시나리오
  • 존재하지 않는 쿠폰에 대한 회수 시나리오
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 258fa76 and 4c25eb5.

📒 Files selected for processing (2)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (1 hunks)
  • src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponEventHandlerTest.java (1 hunks)
🔇 Additional comments (3)
src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (1)

46-46: fetchJoin 추가로 성능 최적화가 이루어졌습니다!

fetchJoin()을 추가하여 N+1 쿼리 문제를 해결하고 LazyInitializationException을 방지했습니다. 이는 쿼리 성능 향상에 도움이 될 것입니다.

src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponEventHandlerTest.java (2)

29-101: 테스트 케이스가 잘 구성되어 있습니다!

스터디 수료 이벤트 처리에 대한 테스트가 다음과 같이 잘 구성되어 있습니다:

  • 기본 쿠폰 발급 시나리오
  • 중복 발급 방지 시나리오
  • 신규 쿠폰 생성 시나리오

각 테스트의 given/when/then 구조가 명확하고, 검증이 적절합니다.


1-132: 테스트 코드의 전반적인 구조가 훌륭합니다!

다음과 같은 좋은 점들이 있습니다:

  • @Nested 클래스를 사용하여 관련 테스트를 논리적으로 그룹화
  • 한글 메서드명을 사용하여 테스트 의도를 명확하게 전달
  • given/when/then 주석을 통한 명확한 테스트 구조화

@@ -43,6 +43,7 @@ public Optional<IssuedCoupon> findUnrevokedIssuedStudyCoupon(CouponType couponTy
return Optional.ofNullable(queryFactory
.selectFrom(issuedCoupon)
.leftJoin(issuedCoupon.coupon, coupon)
.fetchJoin()
Copy link
Member

Choose a reason for hiding this comment

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

조회 대상은 오직 IssuedCoupon이기 때문에, 페치 조인을 수행하고 싶다면 findFetchXXX 와 같은 컨벤션을 지켜야 합니다. 해당 메서드를 사용하는 로직을 보면 coupon 엔티티를 페치 조인해야 할 필요가 없습니다. 통합 테스트에서 어려움이 있다면 별도의 범용성 있는 페치 조인 로직을 추가하는 게 나아보입니다.

Copy link
Member Author

Choose a reason for hiding this comment

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

test에서만 쓰는 메서드를 만들기 애매해서 기존 메서드를 수정했는데
test용 메서드 만드는 쪽으로 수정하겠습니다

Copy link
Member

@kckc0608 kckc0608 left a comment

Choose a reason for hiding this comment

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

lgtm

Copy link

github-actions bot commented Feb 8, 2025

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

Copy link

github-actions bot commented Feb 8, 2025

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

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: 0

🧹 Nitpick comments (1)
src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponQueryMethod.java (1)

56-64: matchesQueryOption 메서드 업데이트 제안

새로 추가된 eqCouponTypeeqStudy 필터를 matchesQueryOption 메서드에도 포함시키는 것이 좋을 것 같습니다. 이를 위해서는 IssuedCouponQueryOption 클래스에도 관련 필드를 추가해야 합니다.

다음과 같이 수정하는 것을 제안드립니다:

    default BooleanBuilder matchesQueryOption(IssuedCouponQueryOption queryOption) {
        return new BooleanBuilder()
                .and(eqStudentId(queryOption.studentId()))
                .and(eqMemberName(queryOption.memberName()))
                .and(eqPhone(queryOption.phone()))
                .and(eqCouponName(queryOption.couponName()))
                .and(hasUsed(queryOption.hasUsed()))
+               .and(eqCouponType(queryOption.couponType()))
+               .and(eqStudy(queryOption.study()))
                .and(hasRevoked(queryOption.hasRevoked()));
    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22c4e1a and 7ce7db2.

📒 Files selected for processing (4)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepository.java (2 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (1 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponQueryMethod.java (2 hunks)
  • src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponEventHandlerTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepository.java
  • src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponEventHandlerTest.java
🔇 Additional comments (2)
src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponQueryMethod.java (2)

34-36: 구현이 잘 되었습니다!

eqCouponType 메서드가 기존 메서드들과 일관된 패턴을 따르고 있으며, null 체크도 적절히 구현되어 있습니다.


38-40: 구현이 잘 되었습니다!

eqStudy 메서드가 기존 메서드들과 일관된 패턴을 따르고 있으며, null 체크도 적절히 구현되어 있습니다.

Copy link

github-actions bot commented Feb 8, 2025

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

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: 0

🧹 Nitpick comments (1)
src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (1)

54-66: 메서드 설계에 대한 제안

  1. findFetchIssuedCoupon 메서드는 fetchJoin 컨벤션을 잘 따르고 있습니다.

  2. 하지만 이전 리뷰 코멘트에서 논의된 것처럼, 테스트 전용 메서드를 별도로 만드는 것이 좋을 것 같습니다. 현재 구현은 범용적인 메서드처럼 보이지만, PR 목적에 따르면 테스트를 위한 것입니다.

  3. findUnrevokedIssuedStudyCoupon와 상당 부분 중복되는 로직이 있습니다.

다음과 같은 개선을 제안드립니다:

-    public Optional<IssuedCoupon> findFetchIssuedCoupon(
-            CouponType couponType, Member member, @Nullable Study study, boolean hasRevoked) {
+    public Optional<IssuedCoupon> findFetchIssuedCouponForTest(
+            CouponType couponType, Member member, @Nullable Study study, boolean hasRevoked) {
         return Optional.ofNullable(queryFactory
                 .selectFrom(issuedCoupon)
                 .leftJoin(issuedCoupon.coupon, coupon)
                 .fetchJoin()
                 .where(eqMember(member)
                         .and(eqStudy(study))
                         .and(hasRevoked(hasRevoked))
                         .and(eqCouponType(couponType)))
                 .fetchFirst());
     }

또는 기존 메서드를 재사용하는 방식을 고려해보세요:

     public Optional<IssuedCoupon> findUnrevokedIssuedStudyCoupon(CouponType couponType, Member member, Study study) {
         return Optional.ofNullable(queryFactory
                 .selectFrom(issuedCoupon)
                 .leftJoin(issuedCoupon.coupon, coupon)
+                .fetchJoin()
                 .where(eqMember(member)
                         .and(coupon.study.eq(study))
                         .and(hasRevoked(false))
                         .and(coupon.couponType.eq(couponType)))
                 .fetchFirst());
     }

-    public Optional<IssuedCoupon> findFetchIssuedCoupon(
-            CouponType couponType, Member member, @Nullable Study study, boolean hasRevoked) {
-        return Optional.ofNullable(queryFactory
-                .selectFrom(issuedCoupon)
-                .leftJoin(issuedCoupon.coupon, coupon)
-                .fetchJoin()
-                .where(eqMember(member)
-                        .and(eqStudy(study))
-                        .and(hasRevoked(hasRevoked))
-                        .and(eqCouponType(couponType)))
-                .fetchFirst());
-    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7ce7db2 and 4ff219c.

📒 Files selected for processing (1)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (2 hunks)
🔇 Additional comments (1)
src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (1)

13-13: LGTM!

Nullable 파라미터를 위한 적절한 어노테이션 임포트입니다.

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class CouponEventHandlerTest extends IntegrationTest {
Copy link
Member

Choose a reason for hiding this comment

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

음 핸들러의 역할과 책임은 그냥 서비스로 delegate 하는 것까지고,
테스트할 대상은 핸들러 내부에서 호출하는 서비스 로직이라고 봐야 하지 않을까요?

Copy link
Member Author

Choose a reason for hiding this comment

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

MentorStudyHistoryServiceTest로 옮길게요

Copy link
Member Author

Choose a reason for hiding this comment

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

test하는 로직이 CouponService에서 돌아가는 것들이니까 CouponServiceTest가 더 적절하겠네요
CouponServiceTest로 옮기고 리뷰 재요청하겠습니다.

Copy link

github-actions bot commented Feb 9, 2025

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

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: 1

🧹 Nitpick comments (1)
src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponServiceTest.java (1)

206-275: 테스트 케이스의 가독성과 견고성을 개선할 수 있습니다.

다음과 같은 개선사항을 제안드립니다:

  1. 각 테스트 메소드에 @DisplayName을 추가하여 테스트의 목적을 명확히 합니다.
  2. 실패 케이스에 대한 테스트도 추가하면 좋을 것 같습니다.
  3. 쿠폰 금액이 정확한지 검증하는 assertion을 추가하면 좋을 것 같습니다.

예시 코드:

 @Nested
+@DisplayName("스터디 수료 쿠폰 발급 테스트")
 class 스터디_수료_쿠폰_발급시 {
     @Test
+    @DisplayName("스터디 수료시 쿠폰이 정상적으로 발급된다")
     void 발급쿠폰을_생성한다() {
         // ...existing code...
         assertThat(coupon.getCouponType()).isEqualTo(CouponType.STUDY_COMPLETION);
         assertThat(coupon.getStudy().getId()).isEqualTo(study.getId());
         assertThat(issuedCoupon.getMember().getId()).isEqualTo(student.getId());
+        assertThat(coupon.getDiscountAmount()).isEqualTo(Money.FIVE_THOUSAND);
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4ff219c and 3a6774e.

📒 Files selected for processing (1)
  • src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponServiceTest.java (2 hunks)
🔇 Additional comments (1)
src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponServiceTest.java (1)

9-20: LGTM! 필요한 import 문들이 잘 추가되었습니다.

도메인 객체와 값 객체들이 적절하게 import 되어 있습니다.

Comment on lines 277 to 303
@Nested
class 스터디_수료_쿠폰_회수시 {

@Test
void 발급쿠폰을_회수한다() {
// given
Member student = createRegularMember();
Member mentor = createMentor();
LocalDateTime now = LocalDateTime.now();
Study study =
createStudy(mentor, Period.of(now.plusDays(5), now.plusDays(10)), Period.of(now.minusDays(5), now));

StudyHistory studyHistory = createStudyHistory(student, study);

couponService.createAndIssueCouponByStudyHistories(List.of(student.getId()));
IssuedCoupon issuedCoupon = issuedCouponRepository
.findFetchIssuedCoupon(CouponType.STUDY_COMPLETION, student, study, false)
.orElseThrow();

// when
couponService.revokeStudyCompletionCouponByStudyHistoryId(student.getId());

// then
issuedCoupon = issuedCouponRepository.findById(issuedCoupon.getId()).orElseThrow();
assertThat(issuedCoupon.getHasRevoked()).isTrue();
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

회수 관련 테스트 케이스를 보강해야 합니다.

다음과 같은 실패 케이스에 대한 테스트를 추가하면 좋을 것 같습니다:

  1. 존재하지 않는 스터디 히스토리 ID로 회수 시도
  2. 이미 사용된 쿠폰 회수 시도
  3. 이미 회수된 쿠폰 재회수 시도

예시 코드:

 @Nested
+@DisplayName("스터디 수료 쿠폰 회수 테스트")
 class 스터디_수료_쿠폰_회수시 {
+    @Test
+    @DisplayName("존재하지 않는 스터디 히스토리로 회수 시도시 예외가 발생한다")
+    void 존재하지_않는_스터디_히스토리로_회수시_실패한다() {
+        // given
+        Long nonExistentStudyHistoryId = 999L;
+
+        // when & then
+        assertThatThrownBy(
+            () -> couponService.revokeStudyCompletionCouponByStudyHistoryId(nonExistentStudyHistoryId))
+            .isInstanceOf(CustomException.class)
+            .hasMessageContaining(STUDY_HISTORY_NOT_FOUND.getMessage());
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Nested
class 스터디_수료_쿠폰_회수시 {
@Test
void 발급쿠폰을_회수한다() {
// given
Member student = createRegularMember();
Member mentor = createMentor();
LocalDateTime now = LocalDateTime.now();
Study study =
createStudy(mentor, Period.of(now.plusDays(5), now.plusDays(10)), Period.of(now.minusDays(5), now));
StudyHistory studyHistory = createStudyHistory(student, study);
couponService.createAndIssueCouponByStudyHistories(List.of(student.getId()));
IssuedCoupon issuedCoupon = issuedCouponRepository
.findFetchIssuedCoupon(CouponType.STUDY_COMPLETION, student, study, false)
.orElseThrow();
// when
couponService.revokeStudyCompletionCouponByStudyHistoryId(student.getId());
// then
issuedCoupon = issuedCouponRepository.findById(issuedCoupon.getId()).orElseThrow();
assertThat(issuedCoupon.getHasRevoked()).isTrue();
}
}
@Nested
@DisplayName("스터디 수료 쿠폰 회수 테스트")
class 스터디_수료_쿠폰_회수시 {
@Test
@DisplayName("존재하지 않는 스터디 히스토리로 회수 시도시 예외가 발생한다")
void 존재하지_않는_스터디_히스토리로_회수시_실패한다() {
// given
Long nonExistentStudyHistoryId = 999L;
// when & then
assertThatThrownBy(
() -> couponService.revokeStudyCompletionCouponByStudyHistoryId(nonExistentStudyHistoryId))
.isInstanceOf(CustomException.class)
.hasMessageContaining(STUDY_HISTORY_NOT_FOUND.getMessage());
}
@Test
void 발급쿠폰을_회수한다() {
// given
Member student = createRegularMember();
Member mentor = createMentor();
LocalDateTime now = LocalDateTime.now();
Study study =
createStudy(mentor, Period.of(now.plusDays(5), now.plusDays(10)), Period.of(now.minusDays(5), now));
StudyHistory studyHistory = createStudyHistory(student, study);
couponService.createAndIssueCouponByStudyHistories(List.of(student.getId()));
IssuedCoupon issuedCoupon = issuedCouponRepository
.findFetchIssuedCoupon(CouponType.STUDY_COMPLETION, student, study, false)
.orElseThrow();
// when
couponService.revokeStudyCompletionCouponByStudyHistoryId(student.getId());
// then
issuedCoupon = issuedCouponRepository.findById(issuedCoupon.getId()).orElseThrow();
assertThat(issuedCoupon.getHasRevoked()).isTrue();
}
}

StudyHistory studyHistory = createStudyHistory(student, study);

// when
couponService.createAndIssueCouponByStudyHistories(List.of(student.getId()));
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
couponService.createAndIssueCouponByStudyHistories(List.of(student.getId()));
couponService.createAndIssueCouponByStudyHistories(List.of(1L));


couponService.createAndIssueCouponByStudyHistories(List.of(student.getId()));

// then
Copy link
Member

Choose a reason for hiding this comment

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

전체 스터디 수료 쿠폰 조회해와서 사이즈만 검증하면 될듯요

StudyHistory studyHistory = createStudyHistory(student, study);

couponService.createAndIssueCouponByStudyHistories(List.of(student.getId()));
IssuedCoupon issuedCoupon = issuedCouponRepository
Copy link
Member

Choose a reason for hiding this comment

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

이건 뭔가요?

Copy link
Member Author

Choose a reason for hiding this comment

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

여기도 위에 있는 리뷰랑 마찬가지로 1L 쓰면 되겠네요
수정했습니다

Copy link

github-actions bot commented Feb 9, 2025

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

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: 0

♻️ Duplicate comments (1)
src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponServiceTest.java (1)

273-296: 🛠️ Refactor suggestion

회수 관련 테스트 케이스를 보강해 주세요.

이전 리뷰에서 제안된 대로, 다음과 같은 실패 케이스에 대한 테스트를 추가하면 좋을 것 같습니다:

  1. 존재하지 않는 스터디 히스토리 ID로 회수 시도
  2. 이미 사용된 쿠폰 회수 시도
  3. 이미 회수된 쿠폰 재회수 시도
+    @Test
+    void 존재하지_않는_스터디_히스토리로_회수시_실패한다() {
+        // given
+        Long nonExistentStudyHistoryId = 999L;
+
+        // when & then
+        assertThatThrownBy(
+            () -> couponService.revokeStudyCompletionCouponByStudyHistoryId(nonExistentStudyHistoryId))
+            .isInstanceOf(CustomException.class)
+            .hasMessageContaining(STUDY_HISTORY_NOT_FOUND.getMessage());
+    }
+
+    @Test
+    void 이미_사용된_쿠폰_회수시_실패한다() {
+        // given
+        setUp();
+        couponService.createAndIssueCouponByStudyHistories(List.of(1L));
+        IssuedCoupon issuedCoupon = issuedCouponRepository.findById(1L).orElseThrow();
+        issuedCoupon.use(LocalDateTime.now());
+
+        // when & then
+        assertThatThrownBy(
+            () -> couponService.revokeStudyCompletionCouponByStudyHistoryId(student.getId()))
+            .isInstanceOf(CustomException.class)
+            .hasMessageContaining(COUPON_NOT_REVOKABLE_ALREADY_USED.getMessage());
+    }
+
+    @Test
+    void 이미_회수된_쿠폰_재회수시_실패한다() {
+        // given
+        setUp();
+        couponService.createAndIssueCouponByStudyHistories(List.of(1L));
+        couponService.revokeStudyCompletionCouponByStudyHistoryId(student.getId());
+
+        // when & then
+        assertThatThrownBy(
+            () -> couponService.revokeStudyCompletionCouponByStudyHistoryId(student.getId()))
+            .isInstanceOf(CustomException.class)
+            .hasMessageContaining(COUPON_NOT_REVOKABLE_ALREADY_REVOKED.getMessage());
+    }
🧹 Nitpick comments (2)
src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponServiceTest.java (2)

211-229: 테스트 검증을 보강해 주세요.

발급된 쿠폰의 개수뿐만 아니라 다음 속성들도 검증하면 좋을 것 같습니다:

  • 발급된 쿠폰의 할인 금액이 정확한지
  • 발급된 쿠폰의 타입이 STUDY_COMPLETION인지
  • 발급된 쿠폰이 올바른 학생에게 할당되었는지
 // then
 Page<IssuedCoupon> issuedCoupons = issuedCouponRepository.findAllIssuedCoupons(
         new IssuedCouponQueryOption(null, null, null, null, null, null), PageRequest.of(0, 10));
 assertThat(issuedCoupons.getTotalElements()).isEqualTo(1L);
+IssuedCoupon issuedCoupon = issuedCoupons.getContent().get(0);
+assertThat(issuedCoupon.getCoupon().getDiscountAmount()).isEqualTo(Money.FIVE_THOUSAND);
+assertThat(issuedCoupon.getCoupon().getType()).isEqualTo(CouponType.STUDY_COMPLETION);
+assertThat(issuedCoupon.getMember().getId()).isEqualTo(student.getId());

211-270: 테스트 코드 중복을 제거해 주세요.

세 개의 테스트 메소드에서 동일한 테스트 데이터 설정 코드가 반복됩니다. @BeforeEach를 사용하여 공통 설정을 추출하면 좋을 것 같습니다.

+    private Member student;
+    private Study study;
+    private StudyHistory studyHistory;
+
+    @BeforeEach
+    void setUp() {
+        Member mentor = createMentor();
+        student = createRegularMember();
+        LocalDateTime now = LocalDateTime.now();
+        study = createStudy(mentor, 
+            Period.of(now.plusDays(5), now.plusDays(10)), 
+            Period.of(now.minusDays(5), now));
+        studyHistory = createStudyHistory(student, study);
+    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3a6774e and 2a95f10.

📒 Files selected for processing (1)
  • src/test/java/com/gdschongik/gdsc/domain/coupon/application/CouponServiceTest.java (2 hunks)

Copy link
Member

@uwoobeat uwoobeat left a comment

Choose a reason for hiding this comment

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

하나만 추가로 봐주세요
lgtm


// then
List<Coupon> coupons = couponRepository.findAll();
assertThat(coupons.size()).isEqualTo(1L);
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
assertThat(coupons.size()).isEqualTo(1L);
assertThat(coupons).hasSize(1);

Copy link

github-actions bot commented Feb 9, 2025

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

@Sangwook02 Sangwook02 merged commit efe4a8f into develop Feb 9, 2025
1 check passed
@Sangwook02 Sangwook02 deleted the test/842-study-completion-coupon-test branch February 9, 2025 09:46
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.

✅ 스터디 수료 쿠폰 관련 테스트 추가
3 participants