Spring Boot:@TestPropertySource 未从导入的配置中加载

Jav*_*ick 5 java spring spring-boot

WebMvcTest在我尝试加载test.properties应用@TestPropertySource注释以覆盖测试类中的某些属性时使用 Spring Boot 1.5.16 。如果我把它放在测试类上,效果就很好:

@RunWith(SpringRunner.class)
@WebMvcTest
@TestPropertySource("classpath:test.properties")
public class ControllerTest {
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是如果我将其移动到导入的配置,则不会加载属性:

@RunWith(SpringRunner.class)
@WebMvcTest
@Import(ControllersConfiguration.class)
public class ControllerTest {
    ...
}
Run Code Online (Sandbox Code Playgroud)

ControllersConfiguration是:

@TestConfiguration
@TestPropertySource("classpath:test.properties")
public class ControllersConfiguration {
    ...
}
Run Code Online (Sandbox Code Playgroud)

你能解释一下这种行为吗?

PS@PropertySource注释在导入的配置中工作,但优先级最低application.properties

UPD:要明确 - 尝试使所有测试通过这里: https: //github.com/Javasick/WeirdTestPropertySource

vla*_*324 5

我昨天调查了一下,发现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);
Run Code Online (Sandbox Code Playgroud)

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

因此,如果您想外部化此注释,您需要创建超类并将此注释放在@Import其上,或者使用此注释创建接口,或者创建您自己的注释,将两个注释结合起来@Import并将@TestPropertySource其放在您的测试类上。