1. 개요

JPA와 같은 지속성 계층에 의존하는 Spring 애플리케이션을 테스트할 때 애플리케이션을 실행하는 데 사용하는 것과는 다른 더 작고 빠른 데이터베이스를 사용하도록 테스트 데이터 소스를 설정하고 싶을 수 있습니다. 테스트가 훨씬 쉬워집니다.

Spring에서 데이터 소스를 구성하려면 DataSource 유형의 bean을 정의해야 합니다 . 이를 수동으로 수행하거나 Spring Boot를 사용하는 경우 표준 애플리케이션 속성을 통해 수행할 수 있습니다.

이 빠른 사용방법(예제)에서는 Spring에서 테스트를 위해 별도의 데이터 소스를 구성하는 여러 가지 방법을 배웁니다 .

2. 메이븐 의존성

Spring JPA 및 테스트를 사용하여 Spring Boot 애플리케이션을 생성할 예정이므로 다음 의존성이 필요합니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> 
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

최신 버전의 spring-boot-starter-data-jpa , h2spring-boot-starter-test는 Maven Central에서 다운로드할 수 있습니다.

이제 테스트를 위해 DataSource를 구성하는 몇 가지 다른 방법을 살펴보겠습니다 .

3. Spring Boot에서 표준 속성 파일 사용

애플리케이션을 실행할 때 Spring Boot가 자동으로 선택하는 표준 속성 파일을 application.properties라고 합니다. src/main/resources 폴더 에 있습니다 .

테스트에 다른 속성을 사용하려는 경우 src/test/resources 에 같은 이름의 다른 파일을 배치하여 기본 폴더 의 속성 파일을 재정의할 수 있습니다 .

src/test/resources 폴더의 application.properties 파일에는 데이터 원본을 구성하는 데 필요한 표준 키-값 쌍이 포함되어 있어야 합니다 . 이러한 속성에는 spring.datasource 접두사가 붙습니다 .

예를 들어 H2 인메모리 데이터베이스를 테스트용 데이터 소스로 구성해 보겠습니다 .

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

Spring Boot는 이러한 속성을 사용하여 DataSource bean을 자동으로 구성합니다.

Spring JPA를 사용하여 매우 간단한 GenericEntity 및 저장소를 정의해 보겠습니다 .

@Entity
public class GenericEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String value;

    //standard constructors, getters, setters
}
public interface GenericEntityRepository
  extends JpaRepository<GenericEntity, Long> { }

다음으로 저장소에 대한 JUnit 테스트를 작성해 보겠습니다 . Spring Boot 애플리케이션의 테스트가 정의한 표준 데이터 소스 속성을 선택하려면 @SpringBootTest 로 어노테이션을 달아야 합니다 .

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootJPAIntegrationTest {
 
    @Autowired
    private GenericEntityRepository genericEntityRepository;

    @Test
    public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
        GenericEntity genericEntity = genericEntityRepository
          .save(new GenericEntity("test"));
        GenericEntity foundEntity = genericEntityRepository
          .findOne(genericEntity.getId());
 
        assertNotNull(foundEntity);
        assertEquals(genericEntity.getValue(), foundEntity.getValue());
    }
}

4. 사용자 지정 속성 파일 사용

표준 application.properties 파일 및 키를 사용하고 싶지 않거나 Spring Boot를 사용하지 않는 경우 사용자 정의 키로 사용자 정의 .properties 파일 을 정의한 다음 @Configuration 클래스 에서 이 파일을 읽어 포함된 값을 기반으로 하는 DataSource 빈 .

이 파일은 애플리케이션의 일반 실행 모드를 위해 src/main/resources 폴더에 배치되고 테스트에서 선택하기 위해 src/test/resources 에 배치됩니다 .

테스트를 위해 H2 메모리 내 데이터베이스를 사용하는 persistence-generic-entity.properties 라는 파일을 만들고 src/test/resources 폴더에 저장해 보겠습니다.

jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.username=sa
jdbc.password=sa

다음으로 속성 소스로 persistence-generic-entity.properties를 로드하는 @Configuration 클래스 에서 이러한 속성을 기반으로 DataSource 빈을 정의할 수 있습니다 .

@Configuration
@EnableJpaRepositories(basePackages = "org.baeldung.repository")
@PropertySource("persistence-generic-entity.properties")
@EnableTransactionManagement
public class H2JpaConfig {
    // ...
}

이 구성에 대한 자세한 예는 메모리 내 데이터베이스를 사용한 자체 포함 테스트에 대한 이전 기사의 "JPA 구성" 섹션을 참조하십시오 .

그런 다음 구성 클래스를 로드한다는 점을 제외하면 이전 테스트와 유사한 JUnit 테스트를 만들 수 있습니다 .

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class, H2JpaConfig.class})
public class SpringBootH2IntegrationTest {
    // ...
}

5. 스프링 프로필 사용

테스트를 위해 별도의 DataSource를 구성할 수 있는 또 다른 방법은 Spring Profile을 활용하여 테스트 프로필 에서만 사용할 수 있는 DataSource bean을 정의하는 것입니다 .

이를 위해 이전과 같이 .properties 파일을 사용하거나 클래스 자체에 값을 쓸 수 있습니다.

테스트에서 로드할 @Configuration 클래스의 테스트 프로필 에 대한 DataSource 빈을 정의해 보겠습니다 .

@Configuration
@EnableJpaRepositories(basePackages = {
  "org.baeldung.repository",
  "org.baeldung.boot.repository"
})
@EnableTransactionManagement
public class H2TestProfileJPAConfig {

    @Bean
    @Profile("test")
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
        dataSource.setUsername("sa");
        dataSource.setPassword("sa");

        return dataSource;
    }
    
    // configure entityManagerFactory
    // configure transactionManager
    // configure additional Hibernate properties
}

그런 다음 JUnit 테스트 클래스에서 @ActiveProfiles 어노테이션을 추가하여 테스트 프로필을 사용하도록 지정해야 합니다 .

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
  Application.class, 
  H2TestProfileJPAConfig.class})
@ActiveProfiles("test")
public class SpringBootProfileIntegrationTest {
    // ...
}

6. 결론

이 짧은 기사에서는 Spring에서 테스트를 위해 별도의 DataSource를 구성하는 여러 가지 방법을 살펴보았습니다 .

항상 그렇듯이 예제의 전체 소스 코드는 GitHub 에서 찾을 수 있습니다 .

res – Persistence (eBook) (cat=Persistence)