テスト用にapplication.propertiesを用意して、テスト時にはそちらを読み込む。
src/resources/application.properties
app.name=props-app
app.comment=this is app:${app.name}
test/resource/application.properties
app.name=props-test
app.comment=this is test:${app.name}
@Valueでインジェクションする
PropsService.java
@Service
public class PropsService {
@Value("${app.name}")
private String appName;
@Value("${app.comment}")
private String appComment;
public String getAppName() {
return appName;
}
public String getComment() {
return appComment;
}
}
@ConfigurationPropertiesで読み込む
- PropsConfig.java
@Component
@ConfigurationProperties(prefix = "app")
public class PropsConfig {
private String name;
private String comment;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
- PropsService.java
@Service
public class PropsService {
@Autowired
PropsConfig propsConfig;
public String getAppName() {
return propsConfig.getName();
}
public String getComment() {
return propsConfig.getComment();
}
}
テストコード
- PropsServiceTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class PropsServiceTest {
@Autowired
PropsService service;
@Test
public void test_getAppName() {
assertThat(service.getAppName()).isEqualTo("props-test");
}
@Test
public void test_getComment() {
assertThat(service.getComment()).isEqualTo("this is test:props-test");
}
}
@SpringBootTestを入れ忘れて読み込まれなくて苦しんだ。