当在Spring Boot中直接在测试类上使用@TestPropertySource
并在元注释上使用时,两个属性源的属性不会合并,而只存在测试类上定义的属性。
JUnit 5 测试:
@CustomTest
@TestPropertySource(properties = "property.b=value-b")
class TestPropertySourceTests {
@Autowired
private Environment environment;
@Test
void testPropertiesFromTestPropertySourcesAreMergedFromTestAndMetaAnnotation() {
assertThat(environment.getProperty("property.a"), is(equalTo("value-a")));
assertThat(environment.getProperty("property.b"), is(equalTo("value-b")));
}
}
元注释:
@Retention(RUNTIME)
@ExtendWith(SpringExtension.class)
@SpringBootTest
@TestPropertySource(properties = "property.a=value-a")
@interface CustomTest {
}
测试失败,property.a
null
而不是value-a
,表明通过元注释定义的属性不存在。
如果两个@TestPropertySource
注释在类层次结构中(即TestPropertySourceTests
将从BaseTests
延伸而来,而又在其自己的@TestPropertySource
中定义了property.a
(
这是有意(并记录在案(的行为吗?有人可能会争辩说,顺序只在类层次结构中定义,而不是在注释树中定义,或者在类层次结构和注释树之间定义。
这是因为当 Spring 引导你的测试上下文时,它只会搜索类型org.springframework.test.context.TestPropertySource
的本地十进制注释。
在此处查看TestPropertySourceUtils
还可以在这里查看MetaAnnotationUtils
if (AnnotationUtils.isAnnotationDeclaredLocally(annotationType, clazz)) {
return new AnnotationDescriptor<>(clazz, clazz.getAnnotation(annotationType));
}
由于它们会立即返回结果,因此没有机会获取您的@CustomTest
注释及其声明的@TestPropertySource
注释。
所以目前是不可能的。
这是春季的设计使然。Sam Brannen 在其他回答中证实了这一点:
- https://stackoverflow.com/a/35748348
- https://stackoverflow.com/a/26183692
我在Spring的跟踪器中打开了一个问题:https://github.com/spring-projects/spring-framework/issues/23299
如果您仍然需要该功能,请投票支持它。