ソフトウェアエンジニアの雑記

日々思ったことをまとめます

@SpringBootTestのときに、@Value("{$spring.profiles.active}")が動作しなかったのでメモ

@SpringBootTestでテスト実行を行ったときに、@Values("${spring.profiles.active}"が取れないってエラーがでたのでメモ。

コード

アプリケーションコードは、単純なRestControllerになります。

@RestController
@RequestMapping("/sample")
public class LineController {

@Value("${spring.profiles.active}")
private String profile

// 省略

}

テストコードも、単純な@SpringBootTestを使ったものなります。

@SpringBootTest
class SampleControllerTest {

  // 省略
}

実行してみると、下記のようなエラーがでます。

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.profiles.active' in value "${spring.profiles.active}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180) ~[spring-core-6.1.6.jar:6.1.6]
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-6.1.6.jar:6.1.6]
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) 
....

${spring.profiles.active}の解決ができていないとログがでています。@SpringBootTestに引数を渡してあげると解決します。

解決方法

@SpringBootTestに引数で、設定値を渡すと解決します。

@SpringBootTest(properties = "spring.profiles.active=unit-test")
class SampleControllerTest {

  // 省略
}

テストを実行すると、値も取得できておりテストも通ります。

割とハマりポイントかなと思いますので、メモになります。