H2 사용해서 Spring Boot 테스트 코드 작성

JangUT·2025년 3월 10일

📌 1. 테스트 코드 작성 시, 구성할 DB 선정

대표적으로 스프링 부트에서 사용되는 DB는 내장형(In-Memory) H2 데이터 베이스
MySQL 데이터 베이스 존재

실제 운영 환경과 따로 테스트 환경을 구축하여 테스트 시 실제 운영환경에 영향을 받지 않도록
H2 데이터 베이스 선택

또한 속도 측면에서 MySQL보다는 H2 DB(In-memory) 환경이 훨씬 속도가 빠르므로 H2 DB 선택

📌 2. H2 BD의 3가지 모드

1. In-Memory Mode (인메모리 모드)

  • 데이터를 메모리에 저장하고 처리하는 모드입니다. 데이터베이스가 메모리 내에서 동작하기 때문에 굉장히 빠른 속도로 데이터를 가져오거나 저장 가능

  • 주로 테스트프로토타이핑 시에 사용되며 데이터는 임시로 유지되며 DB 종료 시 데이터 증발

  • jdbc:h2:mem: 과 같이 URL을 통해 In-Memory 모드를 사용할 수 있습니다.

2. Embedded Mode (내장 모드)

  • 애플리케이션 내부에서 H2 데이터베이스를 내장하여 사용하는 모드입니다.

  • 애플리케이션과 데이터베이스가 같은 JVM에서 동작하기 때문에 별도의 데이터베이스 서버가 필요하지 않습니다.

  • 이 모드 역시 주로 테스트 목적으로 사용되며, 데이터는 애플리케이션 실행 중에 유지됩니다.

  • jdbc:h2:~/test 와 같이 URL을 통해 Embedded 모드를 사용가능

3. Server Mode

  • H2 데이터베이스의 서버를 별도로 실행하고, 다른 애플리케이션들이 네트워크를 통해 해당 서버에 연결하여 사용하는 모드입니다.

  • 여러 클라이언트가 동시에 접근 가능 데이터베이스 영구적으로 유지

  • 서버 모드는 실제 운영환경에서 사용 -> 데이터베이스 관리 및 공유가 필요한 경우 유용

  • jdbc:h2:tcp://localhost/~/test 와 같이 URL을 통해 Server모드를 사용할 수 있습니다.

📌3. In-Memory H2 데이터 베이스 환경 구축

1. build.gradle 의존성 추가


dependencies {

	testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'com.h2database:h2'
}

2. application-test.yml

spring:
  datasource :
    url: jdbc:h2:mem:test
    driverClassName: org.h2.Driver
    username: sa
    password:

  jpa:
    hibernate:
      ddl-auto: create-drop
    database-platform: org.hibernate.dialect.H2Dialect

3. @TestPropertySource 으로 테스트 속성 자료의 위치 선정

@TestPropertySourse(location = "classpath:application-test.yml")

어노테이션을 사용하여, 테스트 시 property sourse의 위치를 설정해줄 수 있습니다.

@TestPropertySourse 사용 예시 코드

@DataJpaTest
@TestPropertySource(locations = "classpath:application-test.yml")
public class ScrapRepositoryTest {

	@Autowired
    private UserRepository userRepository;
    
    @BeforeEach
    void setUp() {
    
    User user = User.builder()
    		.email("test@example.com")
            .password("AAaa!!00")
            .nickname("test")
            .uuid(UUID.randomUUID().toString()).build();
            
            
	userRepository.save(user);

	
    @Test
    @Displayname("이메일로 유저 조회 시 예외 처리")
    void findByEmail_willReturnException() {
    
    	// given
        String email = "exception@example.com";
        
        // when
        Optional<User> user = findByEmail(email);
        
        // then
        Assertions.arrertThatThrowBy(() -> userRepository.findByEmail(email))
        	.isInstanceOf(IllegalArguMentException.class)
            .hasMessage("user dosen't exit")
            
     }
  • 이와 같이 classpath:application-test.yml 경로를 설정하여 testProperties 환경 구축
profile
평범한 개발자

0개의 댓글