在测试中启用配置属性,而无需加载完整的Spring Boot应用程序上下文

时间:2018-11-10 21:11:23

标签: spring spring-boot spring-test

假设我们有Spring Boot应用程序,并且只想加载应用程序上下文的特定部分。

特别加载YAML文件配置并将spring.datasource映射到由DataSourceProperties标记的@ConfigurationProperties

天真无法正常工作的测试声明是:

@RunWith(SpringRunner.class)
@ContextConfiguration(
    classes = {DataSourceAutoConfiguration.class, DataSourceProperties.class},
    loader = AnnotationConfigContextLoader.class,
    initializers = ConfigFileApplicationContextInitializer.class)
@TestPropertySource({"classpath:application.yaml", "classpath:application-dev.yaml"})
@EnableConfigurationProperties({DataSourceProperties.class})
@Slf4j
public class HibernateTest {
    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Test
    public void dataSourceTest() throws SQLException {
        log.info("DS URL: {}", dataSourceProperties.getUrl());
    }
}

application-dev.yaml具有:

spring.datasource:
  url: jdbc:oracle:thin:@localhost:1521/APP

测试打印:

DS URL: null

我正在寻找一种方法,以将YAML配置映射到标记为@ConfigurationProperties的类(DataSourceProperties)上,并使其由@Configuration类(DataSourceAutoConfiguration)使用,而无需加载其他任何方法服务/组件/等...

1 个答案:

答案 0 :(得分:0)

这些链接回答了我的问题:

简而言之,Spring框架开发人员不想为@TestPropertySource@PropertySource注释支持YAML格式,因为注释说明Spring Boot对YAML的支持以棘手的方式/破坏了的方式(尽管我在解释中迷失了方向)

在切换代码以使用.properties文件之后,我的测试正常进行。

相关问题