LoginSignup
77
81

More than 5 years have passed since last update.

Spring Boot - テスト時に読み込むDBを変更する

Last updated at Posted at 2015-02-05

Spring Bootでテストを走らせるときに、開発用・本番用とは違うDBに接続しないなど、設定を変えたい時があります。その場合のは設定方法について。

Test時には、設定ファイルの優先度が変わる

MavenでもGradleでもいいんですが、例えばMavenを使っているならば、Springプロジェクトは以下のような構成になっているはずです。

/my/good/project
 ├── README.md
 ├── pon.xml
 └── src
     ├── main
     │   ├── com
     │   │    └── ...
     │   └── resources
     │       └── application.yml
     └── test
         ├── com
         │    └── ...
         └── resources
             └── application.yml

jarファイルなどにパッケージングして実行した場合はsrc/main/resources/application.ymlを読み込みますが、

mvn test

などと、testを実行した場合はsrc/test/resources/application.ymlが優先的に読み込まれます。(test以下にapplication.yml や application.propertiesがない場合はmainの方にあるやつを反映する)

Testによって更に設定を分岐させる

また、以下のようにして、テストクラス毎に反映する設定ファイルを変えることが出来ます。

/my/good/project
 :
 └── src
     :
     └── test
         ├── com
         │   └── myapp
         │       ├── MyAppIntegrationTest.java
         │       └── MyAppSourceTest.java
         └── resources
             ├── application.yml
             ├── application-unit.yml
             └── application-integration.yml

application.yml
spring:
  profiles.active: unit
application-unit.yml
spring:
  profiles.active: unit
  datasource:
    url: jdbc:mysql://localhost:3306/unit_test_db
application-integration.yml
spring:
  profiles.active: integration
  datasource:
    url: jdbc:mysql://localhost:3306/it_test_db
MyAppTest.java
@ActiveProfiles("unit")
public class MyAppIntegrationTest {
  :
MyAppIntegrationTest.java
@ActiveProfiles("integration")
public class MyAppIntegrationTest {
  :

※ application.yml , application-${profile}.ymlは1つにまとめることも出来ます。1

なんとなく、Spring界隈にのテスト情報がネットには少ない気がします。書籍に頼るしか無いのか…

Packageしたjarの設定ファイルを変更する

mvn package

などとして作成したjarファイルは

java -jar -Dspring.profiles.active=production hoge.jar

とするとspring.profiles.active: productionの設定で実行することが出来ます。

毎回オプションを付けて起動するのが面倒ならば

$ ls
hoge.jar
application.yml

というような構成にしてjava -jar hoge.jarを実行することで、application.ymlの内容を使ってアプリケーションの実行が出来ます。

この情報、どこで見たのか思い出せない…ソースをご存じの方がいたら教えてください!

追記

公式サイト 23.3 Application property filesに説明がありました! @mtn81 thanks!

参考

77
81
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
77
81