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
我昨天调查了一下,发现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
其放在您的测试类上。
归档时间: |
|
查看次数: |
1791 次 |
最近记录: |