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

테스트 시 DB 격리 및 레포지토리 테스트를 위한 베이스 어노테이션 생성 #529

Merged
merged 3 commits into from
Aug 22, 2024

Conversation

jminkkk
Copy link
Contributor

@jminkkk jminkkk commented Aug 21, 2024

⚡️ 관련 이슈

close #469

📍주요 변경 사항

  1. 테스트 시 각 메서드 격리를 위한 DatabaseCleaner 클래스 생성
  • AbstractTestExecutionListener의 beforeTestMethod를 재정의히여 매 테스트 메소드 실행 전 데이터베이스를 클린업하는 로직이 수행되도록 함
  • 클린업하는 로직
    • 모든 테이블을 비우고 외래 키 제약 조건을 일시적으로 비활성화하여 TRUNCATE 작업 수행합니당
  1. @DatabaseIsolation 생성
  • 1번에서 만든 DatabaseCleaner를 테스트 실행 리스너로 추가하고, 기존 리스너들과 병합
  • 쉽게 말해 @DatabaseIsolation 어노테이션을 부착하게 되면 매 테스트 시 DatabaseCleaner가 동작합니다.
  1. DataJpaTest에서 공통적으로 사용될 어노테이션들을 묶은 베이스 어노테이션 @JpaRepositoryTest 생성
  • @DataJpaTest, @DatabaseIsolation 등 레포지토리 단위 테스트 시 필요한 여러 어노테이션을 조합
  • JPA Auditing 기능 사용을 위한 JPA Auditing 설정 파일 import

🎸기타

  1. 테스트 시 데이터베이스 격리를 위해 여러 방법 중 AbstractTestExecutionListener 재정의를 선택한 이유는 아래 블로그 글을 참고하시면 좋을 것 같습니다

앞으로 매 레포지토리 테스트 시 해당 어노테이션을 사용하면 편하실 듯~

@jminkkk jminkkk added refactor 요구사항이 바뀌지 않은 변경사항 zap 리뷰 우선순위가 높은 사항 BE 백엔드 labels Aug 21, 2024
@jminkkk jminkkk added this to the 4차 스프린트 🐔 milestone Aug 21, 2024
@jminkkk jminkkk self-assigned this Aug 21, 2024
@DataJpaTest
@DatabaseIsolation
@Import(JpaAuditingConfiguration.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
Copy link
Contributor Author

@jminkkk jminkkk Aug 21, 2024

Choose a reason for hiding this comment

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

코드가 낯설까봐 추가 코멘트 달아요 🔥
이해 안되시는 부분 있다면 말해주세요 ⚡️


@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) 는 테스트용 인메모리 데이터베이스가 아닌 실제 설정된 데이터베이스를 사용하도록 합니다.

@DataJpaTest이 실행될 때 스프링은 기본적으로 테스트 시 인메모리 데이터베이스 (기존 h2를 사용했을 때처럼 우리 컴퓨터의 메모리에 데이터를 저장하는 DB)로 테스트를 실행 시킵니다.

따라서 우리 테스트 환경인 mysql로 테스트 데이터베이스를 사용하려면 해당 어노테이션을 달아줘야 합니당

import org.springframework.test.context.TestExecutionListeners;

@Retention(RetentionPolicy.RUNTIME)
@TestExecutionListeners(value = DatabaseCleaner.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

이 부분은 우리가 만든 DatabaseCleaner 클래스를 테스트 실행 리스너로 등록한다는 의미입니다.

mergeModes의 MERGE_WITH_DEFAULTS는 우리가 추가한 DatabaseCleaner를 기존 스프링의 기본 리스너들과 함께 사용하겠다는 의미입니다.
(이 모드를 사용하지 않으면, 기본 스프링의 리스너들이 모두 무시되고 DatabaseCleaner만 사용되게 됩니다.)

Copy link
Contributor

@zeus6768 zeus6768 left a comment

Choose a reason for hiding this comment

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

친절한 설명 고마워요 몰리 👍

truncate(queries, jdbcTemplate);
}

private List<String> getTruncateQueries(final JdbcTemplate jdbcTemplate) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
private List<String> getTruncateQueries(final JdbcTemplate jdbcTemplate) {
private List<String> getTruncateQueries(JdbcTemplate jdbcTemplate) {

Copy link
Contributor

@kyum-q kyum-q left a comment

Choose a reason for hiding this comment

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

몰리 짱 수고했어용 ~~ 👍❤️

Copy link
Contributor

@HoeSeong123 HoeSeong123 left a comment

Choose a reason for hiding this comment

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

어려운걸 또 찾아주셨네요.
고생하셨습니다 몰리.

Copy link
Contributor

@zangsu zangsu left a comment

Choose a reason for hiding this comment

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

PR 본문과 링크된 블로그 글 덕분에 수월하게 이해할 수 있었습니다!
고생했어요 몰리!!!

@zangsu zangsu merged commit d0e004d into dev/be Aug 22, 2024
8 checks passed
@zangsu zangsu deleted the refactor/469-add-repository-test branch August 22, 2024 08:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BE 백엔드 refactor 요구사항이 바뀌지 않은 변경사항 zap 리뷰 우선순위가 높은 사항
Projects
Status: Weekend Done
Development

Successfully merging this pull request may close these issues.

5 participants