Spring でUnitTest

単体テスト実行時と本番で構成を変えたい、ということはよくあることだと思います。今はHBaseを絶賛お試し中なので、CIでテストを実行する場合は、リモートのHbaseのCI専用のテーブルに接続する設定にしました。

設定は4カ所

  • src/main/resources/META-INF/spring/ のプロパティファイルの編集
hbase.host=${hbase.host}
hbase.table=${hbase.table}
  • pom.xmlにプロパティ設定とプロファイル追加
<properties>
  <hbase.host>localhost</hbase.host>
  <hbase.table>table</hbase.table>
</properties>
...
<profile>
  <id>ci</id>
  <properties>
    <hbase.host>remotehost</hbase.host>
    <hbase.table>tableci</hbase.table>
  </properties>
 </profile>
  • Javaのコードで
    • 通常のクラスは@Service などのアノテーションが設定すれば@ValueでDI可能
    • テストクラスに@Valueを使ってDIするには、以下のおまじないをテストクラスの宣言の前に書く
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml" })
    • もちろん applicationContextにはプロパティを自動で読み込む設定がされていることが前提。。

これで、

  • プロファイルを設定せずに実行すれば、localhostのtableを操作しにいく
  • mvn -P ci packageと実行した場合は、remotehostのtableciを操作しにいく

設定になっているはずです。