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

인수 테스트에서 테스트 격리하기(테스트 데이터 초기화) #13

Open
Yiseull opened this issue Apr 19, 2024 · 0 comments
Labels
completed Spring test Further information is requested

Comments

@Yiseull
Copy link
Owner

Yiseull commented Apr 19, 2024

문제 상황

공지사항 등록 기능에 대한 인수 테스트를 수행 중입니다. 이 과정에서 서비스가 생성한 공지사항의 ID를 반환받아 테스트에서 해당 값을 확인합니다. 두 개의 테스트 모두 ID 값을 1L로 설정하고 진행했으나, 한 테스트는 성공한 반면 다른 하나는 ID 값이 2L로 나타나며 실패했습니다.

인수 테스트와 @Transactional 사용에 대한 오해

초기에는 구글링을 통해 인수 테스트에서 @Transactional을 사용하면 HTTP 클라이언트 요청과 서버 요청이 다른 스레드에서 처리되어 트랜잭션 롤백이 이루어지지 않는다는 정보를 얻었습니다.

그러나 스프링 공식 문서를 살펴본 결과, 별도의 포트를 지정하지 않았기 때문에 내 상황에는 해당되지 않는다고 판단했습니다. 실제로 테스트를 진행하며 데이터베이스를 확인해 본 결과, 롤백이 정상적으로 이루어졌습니다.

진짜 원인

문제의 진짜 원인은 ID의 자동 증가 값이 트랜잭션 롤백 시에도 롤백되지 않기 때문입니다.

해결 방법

1. TRUNCATE를 사용하여 테스트마다 테이블 초기화

MySQL을 사용하는 경우에는 TRUNCATE만 해줘도 AUTO_INCREMENT 값이 초기화됩니다.

하지만 H2 같은 경우에는 TRUNCATE를 한다고 해서 자동 증가 값이 초기화되지 않습니다. 따라서 아래 명령어를 사용해서 TRUNCATE하면서 자동 증가 값을 같이 초기화해줍니다.

TRUNCATE TABLE notices RESTART IDENTITY;
TRUNCATE TABLE files RESTART IDENTITY;

🚨 h2database 깃허브를 보면 아래 명령어를 사용하려면 MySQL 호환 모드로 해야 한다고 합니다.


참고자료

@Yiseull Yiseull added test Further information is requested Spring labels Apr 19, 2024
@Yiseull Yiseull changed the title 테스트 격리하기(테스트 데이터 초기화) 인수 테스트에서 테스트 격리하기(테스트 데이터 초기화) Apr 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
completed Spring test Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant