Java Spring启动:@TestPropertySource未从导入的配置加载
在Java Spring启动:@TestPropertySource未从导入的配置加载,java,spring,spring-boot,Java,Spring,Spring Boot,在WebMvcTest中使用Spring Boot 1.5.16,我试图加载test.properties应用@TestPropertySource注释,以覆盖测试类中的一些属性。 如果我把它放在测试类上,它就可以正常工作了: @RunWith(SpringRunner.class) @WebMvcTest @TestPropertySource("classpath:test.properties") public class ControllerTest { ... } 但如果将其
WebMvcTest
中使用Spring Boot 1.5.16,我试图加载test.properties
应用@TestPropertySource
注释,以覆盖测试类中的一些属性。
如果我把它放在测试类上,它就可以正常工作了:
@RunWith(SpringRunner.class)
@WebMvcTest
@TestPropertySource("classpath:test.properties")
public class ControllerTest {
...
}
但如果将其移动到导入的配置,则不会加载属性:
@RunWith(SpringRunner.class)
@WebMvcTest
@Import(ControllersConfiguration.class)
public class ControllerTest {
...
}
和控制器配置
类为:
@TestConfiguration
@TestPropertySource("classpath:test.properties")
public class ControllersConfiguration {
...
}
你能解释一下这种行为吗
另外,@PropertySource
注释正在导入的配置中工作,但优先级低于应用程序。属性
UPD:要清楚-请尝试在此处通过所有测试:来自JavaDocs:
如果
配置的上下文加载器支持它
每个SmartContextLoader都是
AbstractGenericContextLoader或AbstractGenericWebContextLoader
提供对@TestPropertySource的自动支持,包括
Spring TestContext提供的每个SmartContextLoader
框架
底线是:
通常,@TestPropertySource将与
@上下文配置
因此,您应该使用
@ContextConfiguration
注释您的测试类。我昨天对它进行了调查,发现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
放在它上面,或者创建与此注释的接口,或者创建您自己的注释,该注释将组合两个注释@Import
和@TestPropertySource
,并将其放在您的测试类上 您是否尝试将@TestPropertySource
的inheritLocations
设置为false
?是的,没有帮助我尝试将@ContextConfiguration
设置为无效。顺便说一句,测试正在工作,但将属性设置为导入的配置-不是我想要的答案