【发布时间】:2020-03-30 03:14:55
【问题描述】:
我需要测试使用 @ConfigurationProperties bean 的自动配置类。我正在使用 https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-test-autoconfig 中记录的 ApplicationContextRunner 来加快测试速度并避免在每个变体之间启动 servlet 容器。但是,使用 @AutoconfigurationProperties 注释的 bean 不会填充注入到 ApplicationContextRunner 中的值。
我怀疑我遇到了类似于https://stackoverflow.com/a/56023100/1484823 的问题
@ConfigurationProperties 不受您在测试中构建的应用程序上下文管理,尽管它们将在应用程序启动时加载,因为您的应用程序主类上有 @EnableConfigurationProperties。
如何使用 ApplicationContextRunner 启用对 @ConfigurationProperties 的支持?
这里是对应的代码
@Test
void ServiceDefinitionMapperPropertiesAreProperlyLoaded() {
ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
SingleServiceDefinitionAnswerAutoConfig.class,
DynamicCatalogServiceAutoConfiguration.class
))
// .withPropertyValues(DynamicCatalogProperties.OPT_IN_PROPERTY + "=true") //Not sure why this seems ignored
.withSystemProperties(DynamicCatalogConstants.OPT_IN_PROPERTY + "=true",
ServiceDefinitionMapperProperties.PROPERTY_PREFIX
+ServiceDefinitionMapperProperties.SUFFIX_PROPERTY_KEY+ "=suffix")
;
contextRunner.run(context -> {
assertThat(context).hasSingleBean(ServiceDefinitionMapperProperties.class);
ServiceDefinitionMapperProperties serviceDefinitionMapperProperties
= context.getBean(ServiceDefinitionMapperProperties.class);
assertThat(serviceDefinitionMapperProperties.getSuffix()).isEqualTo("suffix");
});
}
失败:
org.opentest4j.AssertionFailedError:
Expecting:
<"">
to be equal to:
<"suffix">
but was not.
Expected :suffix
Actual :
<Click to see difference>
at org.springframework.cloud.appbroker.autoconfigure.DynamicCatalogServiceAutoConfigurationTest
public class DynamicCatalogServiceAutoConfiguration {
[...]
@Bean
@ConfigurationProperties(prefix=ServiceDefinitionMapperProperties.PROPERTY_PREFIX, ignoreUnknownFields = false)
public ServiceDefinitionMapperProperties serviceDefinitionMapperProperties() {
return new ServiceDefinitionMapperProperties();
}
[...]
}
ps:我正要向https://github.com/spring-projects/spring-boot/issues 提交一个问题,以建议增强文档以警告ApplicationContext 中的此类限制,并询问打开对@ConfigurationProperties 支持的方法。按照https://raw.githubusercontent.com/spring-projects/spring-boot/master/.github/ISSUE_TEMPLATE.md 的指导,我首先要确保我没有误解这个问题。
【问题讨论】:
标签: spring-boot spring-boot-test