Spring Boot: @TestPropertySource not loaded from imported configuration

时间:2018-12-03 13:24:14

标签: java spring spring-boot

Using Spring Boot 1.5.16 in WebMvcTest I'm trying to load test.properties applying @TestPropertySource annotation in order to override some properties in test class. This works just fine if I put it on test class:

@RunWith(SpringRunner.class)
@WebMvcTest
@TestPropertySource("classpath:test.properties")
public class ControllerTest {
    ...
}

But properties not loaded if I move it to imported configuration:

@RunWith(SpringRunner.class)
@WebMvcTest
@Import(ControllersConfiguration.class)
public class ControllerTest {
    ...
}

and ControllersConfiguration class is:

@TestConfiguration
@TestPropertySource("classpath:test.properties")
public class ControllersConfiguration {
    ...
}

Can you explain that behavior?

P.S. @PropertySource annotation is working in imported configuration, but with lowest precedence than application.properties

UPD: To be clear - try to make all test pass here: https://github.com/Javasick/WeirdTestPropertySource

2 个答案:

答案 0 :(得分:1)

我昨天对其进行了调查,发现Spring仅在以下位置寻找此@TestPropertySource注释:

  • 源测试类
  • 测试类是否实现了接口
  • 该测试班的超级英雄
  • 继承的注释

这是AbstractTestContextBootstrapper.class中负责该代码的一部分:

MergedTestPropertySources mergedTestPropertySources =
        TestPropertySourceUtils.buildMergedTestPropertySources(testClass);
MergedContextConfiguration mergedConfig = new MergedContextConfiguration(testClass,
        StringUtils.toStringArray(locations),
        ClassUtils.toClassArray(classes),
        ApplicationContextInitializerUtils.resolveInitializerClasses(configAttributesList),
        ActiveProfilesUtils.resolveActiveProfiles(testClass),
        mergedTestPropertySources.getLocations(),
        mergedTestPropertySources.getProperties(),
        contextCustomizers, contextLoader, cacheAwareContextLoaderDelegate, parentConfig);

方法TestPropertySourceUtils.buildMergedTestPropertySources(testClass)完全负责从此注释中查找和提取位置。如您所见,Spring仅在测试类上调用它。

因此,如果要外部化此批注,则需要创建超类并将此批注和@Import放在其上,或使用此批注创建接口,或创建将两个批注{{1 }}和@Import并将其放在测试类中。

答案 1 :(得分:-1)

来自JavaDocs:

  

如果启用了@TestPropertySource,则启用@TestPropertySource。   配置的上下文加载器很荣幸。

     

每个SmartContextLoader都是其中一个的子类   AbstractGenericContextLoader或AbstractGenericWebContextLoader   提供对@TestPropertySource的自动支持,其中包括   Spring TestContext提供的每个SmartContextLoader   框架。

底线是:

  

通常,@ TestPropertySource将与   @ContextConfiguration。

因此,您应该使用@ContextConfiguration

注释测试类