
문제: 단위 테스트를 진행할 때 CI/CD 파이프라인에서는 외부 DB에 대한 접근이 제한될 수 있는 문제가 있다.
해결: H2 데이터베이스 사용하여 테스트
Controller → Service → Repository → H2 DataBase효과: 외부 DB 접근에 따른 문제를 해결하고, 테스트의 정확성과 신뢰성을 높일 수 있습니다.
http://h2database.com/html/main.html 에서 설치하고 압축을 풀어준다.
All platforms/h2/bin 경로에서 h2 서버 실행
./h2.sh
실행하면 H2 콘솔 로그인 화면이 실행된다.

http://localhost:8082 주소의 앞부분을 이렇게 바꿔주면 된다.연결 클릭하기
testImplementation 구성을 사용하여 테스트 환경에서만 종속성을 이용하게 한다.
dependencies {
...
testImplementation 'com.h2database:h2'
...
}
spring:
datasource:
url: jdbc:h2:tcp://localhost/~/test
driver-class-name: org.h2.Driver
username: sa
jpa:
show-sql: true
hibernate:
ddl-auto: create
defer-datasource-initialization: true
sql:
init:
data-locations: classpath:db/data.sql
mode: always
INSERT INTO USERS (nickname, email, profile_image, agree_tos, agree_picu, role_type, created_at)
VALUES
('USER1', 'USER1@gmail.com', 'https://i.pinimg.com/564x/58/7d/49/587d49481ac6eeaa0fb1a07a3804d97f.jpg', true, true, 'ADMIN', CURRENT_TIMESTAMP),
('USER2', 'USER2@gmail.com', 'https://i.pinimg.com/564x/58/7d/49/587d49481ac6eeaa0fb1a07a3804d97f.jpg', true, true, 'USER', CURRENT_TIMESTAMP)
@DataJpaTest
@ActiveProfiles("test")
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2, replace = AutoConfigureTestDatabase.Replace.NONE)
public class UserRepositoryTest {
@Autowired
UserRepository userRepository;
@Test
@DisplayName("유저 생성 테스트")
void createUserTest() {
//Given
User user = User.builder()
.email("swm.palindrome@gmail.com")
.nickname("palindrome")
.profileImage("https://palworld.shwa.space/assets/PalIcon/T_PinkCat_icon_normal.png")
.agreeTOS(true)
.agreePICU(true)
.roleType(UserRoleType.ADMIN)
.build();
userRepository.save(user);
//When
User savedUser = userRepository.findByNickname("palindrome");
//Then
assertThat(savedUser.getEmail()).isEqualTo("swm.palindrome@gmail.com");
assertThat(savedUser.getRoleType()).isEqualTo(UserRoleType.ADMIN);
assertThat(savedUser.getCreatedDate()).isNotNull();
}
@Test
@DisplayName("테스트 데이터 조회")
void findAllUsersTest() {
//Given: data.sql
//When
List<User> users = userRepository.findAll();
//Then
assertThat(users).isNotEmpty();
assertThat(users.get(0).getNickname()).isEqualTo("USER1");
assertThat(users.get(1).getNickname()).isEqualTo("USER2");
}
}

참고
H2 Database Engine
스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
H2 DB를 이용한 Mocking 없이 편하게 테스트 하기