2017-08-12 7 views
0

私は、Springテストで、統合テストのためにアプリケーションデータベースの横にあるMySQLテストデータベースを使用したいと考えています。現時点では、H2データベースを自動的に使用しています。これは、GradleにH2依存関係を追加したためです。Spring Bootにテスト用に別のDBを使用するように指示するには?

このテストの例はH2データベースを使用して実行されます。ここでは、物理的なセカンダリデータベースを使用しています。

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.observer.media.model.MediaGroup; 
import org.observer.media.repository.MediaGroupRepository; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.test.context.SpringBootTest; 
import org.springframework.test.context.junit4.SpringRunner; 

import javax.persistence.EntityManager; 
import javax.persistence.PersistenceContext; 

import static org.assertj.core.api.Assertions.assertThat; 

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class MediaGroupServiceTest { 

    @Autowired 
    private MediaGroupService mediaGroupService; 
    @Autowired 
    private MediaGroupRepository mediaGroupRepository; 

    @PersistenceContext 
    private EntityManager entityManager; 

    private MediaGroup mediaGroup = new MediaGroup("name", "ceo", "owner"); 

    @Test 
    public void save() { 
     MediaGroup entity = mediaGroupService.saveNew(mediaGroup); 

     assertThat(mediaGroupRepository.findByName(mediaGroup.getName())).isEqualTo(entity); 
    } 
} 
+3

おそらくhttps://stackoverflow.com/questions/28007686/how-can-i-provide-different-database-configurations-with-spring-bootの複製 – Akash

答えて

0

メインアプリケーションのデータソース設定で/ src/main/java/resourcesにapplication.propertiesがありました。

/src/test/java/resourcesにapplication-test.propertiesを追加し、テストのためにデータソース設定をデータベースに追加しました。さらに、そのデータベースを使用するテストに@ActiveProfiles("test")を追加しました。 Springは、application-test.propertiesとアノテーションのtestという単語を使用して自身を設定することに注意してください。したがって、Springはapplication.propertiesの設定を "上書き"します。

application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/database 
spring.datasource.username=user 
spring.datasource.password=secret 
spring.datasource.driverClassName=com.mysql.jdbc.Driver 

application-test.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/database_test 
spring.datasource.username=user 
spring.datasource.password=secret 
spring.datasource.driver-class-name=com.mysql.jdbc.Driver 
0

質問にはすでに答えを持っていますが。

JPAアプリケーションをテストする場合は、@DataJpaTestも使用できます。デフォルトでは、メモリ内の組み込みデータベースを設定し、@Entityクラスをスキャンし、Spring Data JPAリポジトリを設定します。通常の@Component BeanはApplicationContextにロードされません。

これは、春起動アプリケーションで行われたテストの改善の1つです。

読むドキュメント:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

関連する問題