使用带有integrationTest配置的gradle(3.4.1),即使应用程序正确初始化(./gradlew bootRun),使用Spring Boot的ConfigurationProperties(1.5.1.RELEASE)的测试也无法初始化。使用ConfigurationProperties注释的类与以下
类似@Component
@ConfigurationProperties(prefix = "foo")
@Validated
public class AppConfiguration {
@NonNull
private URL serviceUrl;
...
配置文件确实有getter和setter。生成的错误类似于以下
java.lang.IllegalStateException: Failed to load ApplicationContext
....
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AppConfiguration': Could not bind properties to AppConfiguration
....
Caused by: org.springframework.validation.BindException: org.springframework.boot.bind.RelaxedDataBinder$RelaxedBeanPropertyBindingResult
Field error in object 'foo' on field 'serviceUrl': rejected value [null]; codes ...
集成测试的配置类注释如下
@Configuration
@ComponentScan(...)
@EnableConfigurationProperties
@EnableIntegration
public static class ContextConfiguration {}
答案 0 :(得分:1)
测试类有以下注释
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ReleaseTest {
...
在查看ConfigurationPropertiesBindingPostProcessor#postProcessBeforeInitialization()的Spring Boot代码后,它建议未发现属性源。将 org.springframework.boot:spring-boot-starter-test 工件添加为编译时依赖项,并将测试类的上下文配置修改为
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
使用基于YAML的属性文件正确初始化AppConfiguration类。
另一种方法是添加
@TestPropertySource("classpath:/application.properties")
这种方法并不需要 spring-boot-starter-test 依赖,并且要求传统的"传统的"使用属性文件(YAML文件不适用于此方法)。