テスト用に個別のSpring DataSourceを設定する

テスト用の個別のSpring DataSourceの構成

1. 概要

JPAなどの永続化レイヤーに依存するSpringアプリケーションをテストする場合、テストデータソースを設定して、アプリケーションを実行するために使用するものとは異なる、より小さく高速なデータベースを使用することができます。テストを簡単に実行できるようにします。

Springでデータソースを構成するには、手動で、またはSpring Bootを使用している場合は標準のアプリケーションプロパティを使用して、タイプDataSourceのBeanを定義する必要があります。

このクイックチュートリアルでは、several ways to configure a separate data source for testing in Springを見ていきます。

2. Mavenの依存関係

Spring JPAとテストを使用してSpring Bootアプリケーションを作成するため、次の依存関係が必要になります。


    org.springframework.boot
    spring-boot-starter-data-jpa
    2.1.3.RELEASE


    com.h2database
    h2
    1.4.197


    org.springframework.boot
    spring-boot-starter-test
    2.1.3.RELEASE

spring-boot-starter-data-jpah2、およびspring-boot-starter-testの最新バージョンは、MavenCentralからダウンロードできます。

テスト用にDataSourceを構成するいくつかの異なる方法を見てみましょう。

3. SpringBootでの標準プロパティファイルの使用

Spring Bootがアプリケーションの実行時に自動的に取得する標準のプロパティファイルはapplication.propertiesと呼ばれ、src/main/resourcesフォルダーにあります。

テストに異なるプロパティを使用する場合は、同じ名前の別のファイルをsrc/test/resourcesに配置することで、mainフォルダー内のプロパティファイルをオーバーライドできます。

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はこれらのプロパティを使用して、DataSourceBeanを自動的に構成します。

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 { }

次に、リポジトリの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ファイルを定義し、このファイルを含まれている値に基づいてDataSource Beanを作成するための@Configurationクラス。

このファイルは、アプリケーションの通常の実行モードでは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クラスのDataSourceBeanを定義できます。

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

この構成のより詳細な例については、Self-contained testing with an in-memory databaseに関する以前の記事の「JPA構成」のセクションを参照してください。

次に、構成クラスをロードすることを除いて、前のテストと同様のJUnitテストを作成できます。

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

5. Springプロファイルを使用する

テスト用に個別のDataSourceを構成する別の方法は、Springプロファイルを利用して、testプロファイルでのみ使用可能なDataSourceBeanを定義することです。

このために、以前のように.propertiesファイルを使用するか、クラス自体に値を書き込むことができます。

テストによってロードされる@ConfigurationクラスのtestプロファイルのDataSourceBeanを定義しましょう。

@Configuration
@EnableJpaRepositories(basePackages = {
  "org.example.repository",
  "org.example.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アノテーションを追加して、testプロファイルを使用することを指定する必要があります。

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

6. 結論

このクイックチュートリアルでは、Springでテストするために個別のDataSourceを構成するいくつかの方法を見てきました。

いつものように、例の完全なソースコードはover on GitHubにあります。