Skip to content

Test: [BADA-357] 결제 테스트코드 작성#391

Merged
marineAqu merged 4 commits intodevelopfrom
test/BADA-357-test-trade-community
Aug 5, 2025
Merged

Test: [BADA-357] 결제 테스트코드 작성#391
marineAqu merged 4 commits intodevelopfrom
test/BADA-357-test-trade-community

Conversation

@marineAqu
Copy link
Copy Markdown
Contributor

#️⃣연관된 이슈

close: #380

🚀 작업 내용

  • 결제 테스트 코드 작성

🔍 리뷰 요청 사항

@marineAqu marineAqu added this to the 💰 거래 milestone Aug 5, 2025
@marineAqu marineAqu self-assigned this Aug 5, 2025
@marineAqu marineAqu added the ✅ Test test 관련(storybook, jest...) label Aug 5, 2025
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds comprehensive test coverage for the PaymentService's createOrder and validateIamport methods, along with several improvements to payment handling including better error handling for refunds and payment status updates.

  • Payment service test cases for various error scenarios (deleted posts, sold posts, self-payment, insufficient coins, etc.)
  • Enhanced refund handling with proper payment status updates
  • New REFUNDED payment status and REFUND_FAILED exception type

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
PaymentServiceTest.java New comprehensive test file covering payment validation scenarios
PaymentService.java Enhanced validateIamport method with better payment status management and refund handling
TradeException.java Added new REFUND_FAILED exception for refund operation failures
PaymentStatus.java Added REFUNDED status to payment status enum
Comments suppressed due to low confidence (6)

src/test/java/com/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java:317

  • The variable name 'portonePayment' is inconsistent with the naming convention used elsewhere. It should be 'portOnePayment' to match the existing pattern in the codebase (like 'portOneResponse').
        given(portonePayment.getStatus()).willReturn(status);

src/test/java/com/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java:311

  • The variable name 'portonePayment' is inconsistent with the naming convention used elsewhere. It should be 'portOnePayment' to match the existing pattern in the codebase (like 'portOneResponse').
        com.siot.IamportRestClient.response.Payment portonePayment = mock(com.siot.IamportRestClient.response.Payment.class);

src/test/java/com/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java:318

  • The variable name 'portonePayment' is inconsistent with the naming convention used elsewhere. It should be 'portOnePayment' to match the existing pattern in the codebase (like 'portOneResponse').
        given(portonePayment.getAmount()).willReturn(amount);

src/test/java/com/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java:315

  • The variable name 'portonePayment' is inconsistent with the naming convention used elsewhere. It should be 'portOnePayment' to match the existing pattern in the codebase (like 'portOneResponse').
        given(portOneResponse.getResponse()).willReturn(portonePayment);

src/test/java/com/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java:316

  • The variable name 'portonePayment' is inconsistent with the naming convention used elsewhere. It should be 'portOnePayment' to match the existing pattern in the codebase (like 'portOneResponse').
        given(portonePayment.getImpUid()).willReturn(impUid);

src/main/java/com/TwoSeaU/BaData/domain/trade/exception/TradeException.java:54

  • Missing semicolon after the last enum entry. The line should end with a semicolon to maintain consistency with Java enum syntax.
    REFUND_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, 3042, "환불에 실패했습니다.")

@github-actions
Copy link
Copy Markdown

github-actions bot commented Aug 5, 2025

Failed to generate code suggestions for PR

@github-actions
Copy link
Copy Markdown

github-actions bot commented Aug 5, 2025

Overall Project 19.11% -0.15%
Files changed 64.91%

File Coverage
PaymentStatus.java 100% 🍏
PaymentService.java 34.68% -5.38%

@marineAqu marineAqu merged commit 7d028ff into develop Aug 5, 2025
1 check passed
@marineAqu marineAqu deleted the test/BADA-357-test-trade-community branch August 5, 2025 11:06
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Aug 5, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

이번 변경 사항에서는 결제 상태를 나타내는 PaymentStatus enum에 REFUNDED 상수가 추가되었습니다. 거래 예외를 관리하는 TradeException enum에도 환불 실패를 나타내는 REFUND_FAILED 상수가 새로 도입되었습니다. PaymentService 클래스에서는 결제 취소 및 검증 로직이 수정되어, 검증 실패 시 결제 상태를 REFUNDED로 업데이트하도록 변경되었습니다. 또한, 결제 서비스의 주요 예외 및 검증 로직을 다루는 단위 테스트 클래스 PaymentServiceTest가 새로 추가되어 다양한 실패 시나리오를 검증합니다. 마지막으로, GetMerchantUidRequest 클래스에 Lombok의 @Builder 애노테이션이 추가되어 빌더 패턴을 지원하며, import 구문이 정리되었습니다.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 91041dd and c53f369.

📒 Files selected for processing (1)
  • src/main/java/com/TwoSeaU/BaData/domain/trade/dto/request/GetMerchantUidRequest.java (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch test/BADA-357-test-trade-community

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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

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 generate unit tests to generate unit tests for 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
Copy Markdown

@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/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java (1)

310-321: 추가 검증 시나리오 고려 제안.

현재 테스트는 기본적인 실패 시나리오를 잘 다루고 있지만, PaymentService의 새로운 환불 로직(payment.updatePaymentStatus(PaymentStatus.REFUNDED))에 대한 테스트가 누락되어 있습니다.

다음과 같은 테스트 케이스 추가를 고려해보세요:

  • 게시글 삭제/판매 완료 시 환불 처리 및 상태 업데이트 검증
  • 결제 금액 불일치 시 환불 처리 검증
  • 코인 부족 시 환불 처리 검증

이를 통해 새로 추가된 REFUNDED 상태 업데이트 로직의 동작을 확인할 수 있습니다.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fc14696 and 91041dd.

📒 Files selected for processing (4)
  • src/main/java/com/TwoSeaU/BaData/domain/trade/enums/PaymentStatus.java (1 hunks)
  • src/main/java/com/TwoSeaU/BaData/domain/trade/exception/TradeException.java (1 hunks)
  • src/main/java/com/TwoSeaU/BaData/domain/trade/service/PaymentService.java (2 hunks)
  • src/test/java/com/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: dionisos198
PR: Ureca-Final-Project-Team2/be_badata#172
File: src/main/java/com/TwoSeaU/BaData/domain/rental/entity/Reservation.java:73-75
Timestamp: 2025-07-21T04:29:30.585Z
Learning: Reservation 엔티티의 changePrice 메서드에서 price 파라미터에 대한 null 검증은 불필요하다. null 값은 DB 제약조건(NOT NULL)에 의해 처리되고, 음수 가격은 비즈니스 로직에서 방지된다.
Learnt from: marineAqu
PR: Ureca-Final-Project-Team2/be_badata#269
File: src/main/java/com/TwoSeaU/BaData/domain/trade/controller/MockController.java:24-27
Timestamp: 2025-07-28T01:53:53.618Z
Learning: marineAqu prefers to keep method names as-is in temporary Mock APIs that are planned for deletion, prioritizing development efficiency over perfect naming conventions for code that will be removed later.
Learnt from: marineAqu
PR: Ureca-Final-Project-Team2/be_badata#365
File: src/main/java/com/TwoSeaU/BaData/domain/trade/service/PostSearchService.java:44-44
Timestamp: 2025-08-03T14:04:42.957Z
Learning: marineAqu는 개별 API의 완벽한 구현보다는 모든 API 간의 일관된 구현 패턴을 유지하는 것을 우선시한다. 보안이나 성능 개선 사항이 있더라도 전체 시스템에 대한 논의 후 일괄 적용하는 것을 선호한다.
Learnt from: marineAqu
PR: Ureca-Final-Project-Team2/be_badata#358
File: src/main/java/com/TwoSeaU/BaData/domain/trade/service/RecommendService.java:155-169
Timestamp: 2025-08-03T04:35:46.490Z
Learning: marineAqu는 곧 삭제될 예정인 API의 경우, 최적화보다는 개발 효율성을 우선시하여 현재 구현을 임시로 유지하는 것을 선호한다. 삭제될 코드에 대해서는 완벽한 구현보다는 개발 속도를 중시한다.
📚 Learning: in java, when classes are in the same package, no import statement is needed. classes in the same pa...
Learnt from: marineAqu
PR: Ureca-Final-Project-Team2/be_badata#118
File: src/main/java/com/TwoSeaU/BaData/domain/trade/entity/Payment.java:32-32
Timestamp: 2025-07-15T06:31:54.894Z
Learning: In Java, when classes are in the same package, no import statement is needed. Classes in the same package can reference each other directly without explicit imports. This applies to the Post entity in the Payment.java file where both are in the com.TwoSeaU.BaData.domain.trade.entity package.

Applied to files:

  • src/main/java/com/TwoSeaU/BaData/domain/trade/service/PaymentService.java
  • src/test/java/com/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java
📚 Learning: marineaqu는 ela 서비스에서 이미 exception 처리가 구현되어 있어서 postservice의 e3test() 메서드에서 추가적인 ela 실패 처리가 불필요하다고 설명...
Learnt from: marineAqu
PR: Ureca-Final-Project-Team2/be_badata#223
File: src/main/java/com/TwoSeaU/BaData/domain/trade/service/PostService.java:73-78
Timestamp: 2025-07-25T05:17:30.078Z
Learning: marineAqu는 ELA 서비스에서 이미 Exception 처리가 구현되어 있어서 PostService의 E3Test() 메서드에서 추가적인 ELA 실패 처리가 불필요하다고 설명했다. 중복 처리를 피하는 것을 선호한다.

Applied to files:

  • src/test/java/com/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java
🔇 Additional comments (9)
src/main/java/com/TwoSeaU/BaData/domain/trade/enums/PaymentStatus.java (1)

9-9: REFUNDED 상태 추가가 적절합니다.

결제 환불 상태를 명확히 구분하기 위한 새로운 상수 추가가 합리적입니다. PaymentService의 환불 로직과 잘 연계됩니다.

src/main/java/com/TwoSeaU/BaData/domain/trade/exception/TradeException.java (1)

54-54: 환불 실패 예외 추가가 적절합니다.

REFUND_FAILED 예외를 PAYMENT_FAILED와 별도로 구분하여 더 구체적인 에러 처리가 가능해졌습니다. HTTP 상태와 에러 코드도 적절합니다.

src/main/java/com/TwoSeaU/BaData/domain/trade/service/PaymentService.java (3)

117-117: 환불 실패 예외 변경이 적절합니다.

PAYMENT_FAILED에서 REFUND_FAILED로 변경하여 환불 실패와 결제 실패를 명확히 구분하게 되었습니다.


134-136: Payment 조회 위치 개선이 좋습니다.

Payment 엔티티 조회를 검증 로직 초기에 배치하여 중복 조회를 방지하고 코드 효율성을 개선했습니다.


139-139: 환불 상태 업데이트 로직이 일관적입니다.

검증 실패 시나리오에서 결제 취소 후 PaymentStatus.REFUNDED로 상태를 업데이트하는 로직이 일관되게 적용되어 데이터 일관성을 보장합니다.

Also applies to: 145-145, 155-155, 161-161

src/test/java/com/TwoSeaU/BaData/domain/trade/service/PaymentServiceTest.java (4)

41-64: 테스트 설정이 적절합니다.

MockitoExtension과 적절한 Mock 객체 설정으로 단위 테스트 환경이 잘 구성되었습니다. @ActiveProfiles("test")로 테스트 프로파일도 올바르게 설정되었습니다.


66-241: createOrder 테스트 케이스가 포괄적입니다.

다음 시나리오들을 모두 테스트하여 높은 커버리지를 달성했습니다:

  • 삭제된 게시글 접근
  • 이미 판매된 게시글
  • 본인 게시글 구매 시도
  • 코인 부족
  • 소수점 코인 사용
  • 코인이 가격 초과

각 테스트는 적절한 예외와 메시지를 검증합니다.


243-295: validateIamport 테스트가 핵심 시나리오를 다룹니다.

결제 상태가 "paid"가 아닌 경우와 결제 내역을 찾을 수 없는 경우의 예외 처리를 적절히 테스트했습니다.


297-321: 헬퍼 메서드가 잘 설계되었습니다.

createTestPostcreatePortOneResponse 메서드가 테스트 데이터 생성을 효율적으로 처리하고 있습니다. Mock 객체 설정도 적절합니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✅ Test test 관련(storybook, jest...)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BADA-357] [TEST] 거래 커뮤니티 테스트 코드 작성

3 participants